C++ Map 中的 find函数

首页 / C++入门教程 / C++ Map 中的 find函数

C++映射 find()函数用于查找具有给定键值k 的元素。如果找到该元素,则返回指向该元素的迭代器。否则,它返回一个指向映射末尾的迭代器,即map :: end()。

find - 语法

 iterator find (const key_type& k);            //until C++ 11
const_iterator find (const key_type& k) const;    //since C++ 11

find - 参数

k :它指定要在映射集合中搜索的键。

find - 返回值

如果找到该元素,则返回指向该元素的迭代器。否则,它会返回一个指向映射末尾的迭代器,即map::end()。

find - 例子1

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

#include <iostream>
#include <map>
using namespace std;
int main(void) {
   map<char, int> m = {
            {'a', 100},
            {'b', 200},
            {'c', 300},
            {'d', 400},
            {'e', 500},
            };

   auto it = m.find('c');

   cout << "Iterator points to " << it->first << 
      " = " << it->second << endl;

   return 0;
}

输出:

Iterator points to c = 300

在上面的示例中,find()函数返回给定键值'c'的值。

find - 例子2

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

#include <iostream>
#include <map>
using namespace std;
int main(void) {
   map<char, int> m = {
            {'a', 100},
            {'b', 200},
            {'c', 300},
            {'d', 400},
            {'e', 500},
            };
            
    auto it = m.find('e');
   
    if ( it == m.end() ) {
   //not found
     cout<<"Element not found";
    } 
    else {
       //found
        cout << "Iterator points to " << it->first << " = " << it->second << endl;
    }
    
   return 0;
}

输出:

Iterator points to e = 500

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

无涯教程网

find - 例子3

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

#include <iostream>
#include <map>
 using namespace std;
int main()
{
    int n;
    map<int,char> example = {{1,'a'},{2,'b'},{3,'c'},{4,'d'},{5,'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->first << " = " << search->second << '\n';
    } else {
        cout << n<<" not found\n";
    }
}

输出:

Enter the element which you want to search: 4
4 found and the value is 4 = d

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

find - 例子4

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

#include <iostream>
#include <map>

using namespace std;

int main ()
{
  map<char,int> mymap;
  map<char,int>::iterator it;

  mymap['a']=50;
  mymap['b']=100;
  mymap['c']=150;
  mymap['d']=200;

  it = mymap.find('b');
  if (it != mymap.end())
    mymap.erase (it);

 //print content:
  cout << "elements in mymap:" << '\n';
  cout << "a => " << mymap.find('a')->second << '\n';
  cout << "c => " << mymap.find('c')->second << '\n';
  cout << "d => " << mymap.find('d')->second << '\n';

  return 0;
}

输出:

elements in mymap:
a => 50
c => 150
d => 200

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

技术教程推荐

深入浅出区块链 -〔陈浩〕

研发效率破局之道 -〔葛俊〕

性能测试实战30讲 -〔高楼〕

跟月影学可视化 -〔月影〕

物联网开发实战 -〔郭朝斌〕

实用密码学 -〔范学雷〕

如何成为学习高手 -〔高冷冷〕

云计算的必修小课 -〔吕蕴偲〕

AI绘画核心技术与实战 -〔南柯〕

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