C++ unordered_multimap::find() 函数



C++ 的std::unordered_multimap::find()函数用于查找与键k关联的元素。如果操作成功,则方法返回指向该元素的迭代器;否则,返回指向multimap::end()的迭代器。

语法

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

iterator find (const key_type& k); const_iterator find (const key_type& k) 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.

返回值

如果找到指定的键,则返回指向该元素的迭代器;否则,返回multimap::end()迭代器。

示例 1

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

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

输出

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

Iterator points to d = 6

示例 2

考虑下面的示例,我们将查找值为偶数的键值对。

Open Compiler
#include <iostream> #include <unordered_map> using namespace std; int main(void) { unordered_multimap<char, int> um = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}, {'f', 6}, }; 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; }

输出

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

f = 6
d = 4
b = 2

示例 3

让我们看看下面的示例,我们将创建一个接受输入字符串的输入字符串,如果输入键在multimap中可用,则返回其键值,否则返回“未找到”。

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

输出

以下是输入在multimap中可用时的输出。

who? John
John is 60.4

输出

以下是输入不可用时的输出:

who? Aman
not found

示例 4

下面的示例演示了如何使用find()函数搜索指定键的元素。

Open Compiler
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main () { unordered_multimap<string,int> umm = { {"John",1}, {"Vaibhaw",2}, {"Sunny",3}, {"John",4} }; if (auto it = umm.find("John"); it != umm.end()) cout << "Found " << it->first << " " << it->second << '\n'; else cout << "Not found\n"; return 0; }

输出

以上代码的输出如下:

Found John 4
广告