C ++ map find()函數(shù)用于查找具有給定鍵值k 的元素。如果找到該元素,則返回指向該元素的迭代器。否則,它返回一個指向map末尾的迭代器,即map :: end()。
iterator find (const key_type& k); // 在 C++ 11 之前 const_iterator find (const key_type& k) const; //從 C++ 11 開始
k:指定要在map容器中搜索的鍵。
如果找到該元素,則返回指向該元素的迭代器。否則,它返回一個指向map末尾的迭代器,即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 << "迭代器指向 " << it->first <<
" = " << it->second << endl;
return 0;
}輸出:
迭代器指向 c = 300
在上面的示例中,find()函數(shù)返回給定鍵值'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() ) {
cout<<"找不到元素";
}
else {
// 找到元素
cout << "迭代器指向 " << it->first << " = " << it->second << endl;
}
return 0;
}輸出:
迭代器指向 e = 500
在上面的示例中,find()函數(shù)在map容器m中找到鍵值e,如果在map中未找到鍵值e,則它將返回未找到消息,否則將顯示該map。
讓我們看一個簡單的實例。
#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<<"輸入您要搜索的元素: ";
cin>>n;
auto search = example.find(n);
if (search != example.end()) {
cout << n<<" 找到,值是 " << search->first << " = " << search->second << '\n';
} else {
cout << n<<" 未找到\n";
}
}輸出:
輸入您要搜索的元素: 5 5 找到,值是 5 = e
在上面的示例中,使用find()函數(shù)根據(jù)用戶給定的鍵值查找元素。
讓我們看一個簡單的實例。
#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);
cout << "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;
}輸出:
mymap中的元素: a => 50 c => 150 d => 200