#include <unordered_map> unordered_map<string, int> dist; dist.count(x) == 1;//x元素存在 dist.count(x) == 0;//x元素不存在 //2 利用find dist.find(x) != dist.end();//x元素存在 dist.find(x) == dist.end();//x元素不存在 //3 利用迭代器遍历 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元素不存在
示例代码,
#include <iostream> #include <unordered_map> using namespace std; void method1(unordered_map<string, int> dist, string x) { if(dist.count(x) == 1) cout << "键值对dist中存在" << x << "!" << endl; else cout << "键值对dist中不存在" << x << "!" << endl; } void method2(unordered_map<string, int> dist, string x) { if(dist.find(x) != dist.end()) cout << "键值对dist中存在" << x << "!" << endl; else cout << "键值对dist中不存在" << x << "!" << endl; } void method3(unordered_map<string, int> dist, string x) { unordered_map<string, int>::iterator it = dist.begin(); bool IsExist = false; while(it != dist.end()) { if(it->first == x) { IsExist = true; break; } it++; } if(IsExist) cout << "键值对dist中存在" << x << "!" << endl; else cout << "键值对dist中不存在" << x << "!" << endl; } int main() { unordered_map<string, int> dist; dist["Chinese"] = 1; dist["math"] = 2; dist["English"] = 3; dist["physics"] = 4; dist["chemistry"] = 5; dist["biology"] = 6; //1 利用count cout << "1利用count: " << endl; method1(dist, "Chinese"); method1(dist, "history"); //2 利用find cout << "2利用find: " << endl; method2(dist, "Chinese"); method2(dist, "history"); //3 利用迭代器遍历 cout << "3利用迭代器遍历: " << endl; method3(dist, "Chinese"); method3(dist, "history"); return 0; }
输出为,
1利用count: 键值对dist中存在Chinese! 键值对dist中不存在history! 2利用find: 键值对dist中存在Chinese! 键值对dist中不存在history! 3利用迭代器遍历: 键值对dist中存在Chinese! 键值对dist中不存在history!