C++ Set 中的 Find函数

首页 / C++入门教程 / C++ Set 中的 Find函数

C++设置 find()函数用于查找具有给定值的元素。如果找到该元素,则返回指向该元素的迭代器,否则,返回指向集合末尾的迭代器,即set::end()。

Find - 语法

iterator find (const value_type& val) const;                 //until C++ 11
const_iterator find (const value_type& val) const;              //since C++ 11
iterator       find (const value_type& val);                    //since C++ 11

Find - 参数

val :指定要在集合集合中搜索的值。

Find - 返回值

如果找到该元素,则返回指向该元素的迭代器,否则,返回指向集合末尾的迭代器,即set :: end()。

Find - 例子1

让我们看一个简单的示例,查找具有给定键值的元素:

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-find-function.html

来源:LearnFk无涯教程网

#include <iostream>
#include <set>

using namespace std;

int main(void) {
   set<int> m = {100,200,300,400};

   auto it = m.find(300);

   cout << "Iterator points to " << *it << endl;

   return 0;
}

输出:

Iterator points to 300

Find - 例子2

让我们看一个简单的示例来查找元素:

无涯教程网

#include <iostream>
#include <set>

using namespace std;

int main(void) {
   set<char> m = {'a', 'b', 'c', 'd'};

            
    auto it = m.find('e');
   
    if ( it == m.end() ) {
   //not found
     cout<<"Element not found";
    } 
    else {
       //found
        cout << "Iterator points to " << *it<< endl;
    }
    
   return 0;
}

输出:

Element not found

在上面的示例中,find()函数在集合m中查找键值e,如果在集合m中找不到键值e,则它将返回未找到消息,否则将显示集合。

Find - 例子3

让我们看一个简单的例子:

#include <iostream>
#include <set>
 
using namespace std;

int main()
{
    char n;
    set<char> example = {'a','b','c','d','e'};
    
    cout<<"Enter the element which you want to search: ";
    cin>>n;
 
    auto search = example.find(n);
    if (search != example.end()) {
        cout << n<<" found and the value is " << *search << '\n';
    } else {
        cout << n<<" not found\n";
    }
}

输出:

Enter the element which you want to search: b
b found and the value is b

在上面的示例中,使用find()函数根据用户的给定值查找元素。

Find - 例子4

让我们看一个简单的例子:

#include <iostream>
#include <set>

int main () {
   std::set<int> myset;
   std::set<int>::iterator it;

   for (int i = 1; i <= 10; i++) myset.insert(i*10);    
   it = myset.find(40);
   myset.erase (it);
   myset.erase (myset.find(60));

   std::cout << "myset contains:";
   for (it = myset.begin(); it!=myset.end(); ++it)
      std::cout << ' ' << *it;
   std::cout << '\n';

   return 0;
}

输出:

myset contains: 10 20 30 50 70 80 90 100

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Nginx核心知识150讲 -〔陶辉〕

Linux实战技能100讲 -〔尹会生〕

Elasticsearch核心技术与实战 -〔阮一鸣〕

乔新亮的CTO成长复盘 -〔乔新亮〕

A/B测试从0到1 -〔张博伟〕

说透芯片 -〔邵巍〕

说透5G -〔杨四昌〕

搞定音频技术 -〔冯建元 〕

Serverless进阶实战课 -〔静远〕

好记忆不如烂笔头。留下您的足迹吧 :)