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

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

#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

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

技术教程推荐

左耳听风 -〔陈皓〕

持续交付36讲 -〔王潇俊〕

MySQL实战45讲 -〔林晓斌〕

OpenResty从入门到实战 -〔温铭〕

零基础实战机器学习 -〔黄佳〕

手把手带你搭建秒杀系统 -〔佘志东〕

手把手带你写一个 MiniTomcat -〔郭屹〕

互联网人的数字化企业生存指南 -〔沈欣〕

Midjourney入门实践课 -〔Jovi〕

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