C++ unordered_map::find() 函数



C++ 的std::unordered_map::find()函数用于查找与键k关联的元素,如果找到则返回一个迭代器,或者它找到一个键等价于键的元素。

如果操作成功,则方法返回指向元素的迭代器,否则返回指向map::end()的迭代器。

语法

以下是std::unordered_map::find()函数的语法。

const_iterator find(const Key& keyval) const;

参数

  • k - 表示要搜索的键值。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

返回值

如果找到指定的键,则返回一个指向该元素的迭代器;否则,返回一个超出末尾的(map::end())迭代器。

示例 1

在以下示例中,我们演示了std::unordered_map::find()函数的使用。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map<char, int> um = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5} }; auto it = um.find('d'); cout << "Iterator points to " << it->first << " = " << it->second << endl; return 0; }

输出

如果我们运行以上代码,它将生成以下输出:

Iterator points to d = 4

示例 2

考虑以下示例,我们创建一个无序映射,用于存储15ae键关联的值,并查找值为偶数的键/值对。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_map<char, int> um = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5} }; for(auto it = um.begin(); it!=um.end(); ++it){ if(it->second % 2 == 0){ it = um.find(it->first); cout<<it->first<<" = "<<it->second<<endl; } } return 0; }

输出

让我们编译并运行以上程序,这将产生以下结果:

d = 4
b = 2

示例 3

以下是一个示例,我们创建一个无序映射并获取一个输入字符串;如果输入键在映射中可用,则返回其键值对,否则返回“未找到”。

Open Compiler
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main () { unordered_map<string,double> mymap = { {"John",55.4}, {"Vaibhav",65.1}, {"Sunny",50.9} }; string input; cout << "who? "; getline (cin,input); auto got = mymap.find (input); if ( got == mymap.end() ) cout << "not found"; else cout << got->first << " is " << got->second; return 0; }

输出

以下是当我们的输入在映射中可用时的输出。

who? Vaibhav
Vaibhav is 65.1

以下是当我们的输入在映射中不可用时的输出

who? Aman
not found
广告