当所查找的关键key出现时,它返回数据所在对象的位置,如果沒有,返回iter与end函数的值相同。
// find 返回迭代器指向当前查找元素的位置否则返回map::end()位置
iter = mapStudent.find("123");
if(iter != mapStudent.end())
cout<<"Find, the value is"<<iter->second<<endl;
else
cout<<"Do not Find"<<endl;
一、利用find
#include <unordered_map>
unordered_map<string, int> dist;
dist.find(x) != dist.end();//x元素存在
dist.find(x) == dist.end();//x元素不存在
// map::find
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
std::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:
std::cout << "elements in mymap:" << '\n';
std::cout << "a => " << mymap.find('a')->second << '\n';
std::cout << "c => " << mymap.find('c')->second << '\n';
std::cout << "d => " << mymap.find('d')->second << '\n';
return 0;
}
elements in mymap:
a => 50
c => 150
d => 200
二、利用count
#include <unordered_map>
unordered_map<string, int> dist;
dist.count(x) == 1;//x元素存在
dist.count(x) == 0;//x元素不存在
三、利用迭代器遍历
#include <unordered_map>
unordered_map<string, int> dist;
unordered_map<string, int>::iterator it = dist.begin();
bool IsExist = false;
while(it != dist.end())
{
if(it->first == x)
{
IsExist = true;
break;
}
it++;
}
IsExist == true;//x元素存在
IsExist == false;//x元素不存在
C++中map.find()函数_dutmathjc的博客-CSDN博客_map.find
C++(14):判断map中key值是否存在_Just_like_fire的博客-CSDN博客_判断map中key是否存在