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()。
让我们看一个简单的示例,查找具有给定键值的元素。
#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'的值。
让我们看一个简单的示例来查找元素。
#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,则它返回未找到消息,否则将显示该映射。
让我们看一个简单的例子。
#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()函数根据用户给定的键值查找元素。
让我们看一个简单的例子。
#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
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)