C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ Map find()

C++ Map find()函数

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

语法

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

参数

k : 它指定要在地图容器中搜索的键。

返回值

如果找到元素,则返回指向该元素的迭代器。否则,它将返回一个指向地图末端的迭代器,即map :: end()。

示例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'的值。

示例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,如果在映射m中找不到键值e,则返回未找到消息,否则将显示该映射。

示例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()函数根据用户给定的键值查找元素。

示例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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4