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 − 表示要搜尋的鍵。

返回值

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

示例 1

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

#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

考慮下面的示例,我們將查詢值為偶數的鍵值對。

#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中可用,則返回其鍵值,否則返回“未找到”。

#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()函式搜尋指定鍵的元素。

#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
廣告