C++ unordered_map::find() 函式



C++ 的std::unordered_map::find()函式用於查詢與鍵k關聯的元素,如果找到則返回一個迭代器,或者它找到一個鍵等價於鍵的元素。

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

語法

以下是std::unordered_map::find()函式的語法。

const_iterator find(const Key& keyval) const;

引數

  • k - 表示要搜尋的鍵值。

返回值

如果找到指定的鍵,則返回一個指向該元素的迭代器;否則,返回一個超出末尾的(map::end())迭代器。

示例 1

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

#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鍵關聯的值,並查詢值為偶數的鍵/值對。

#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

以下是一個示例,我們建立一個無序對映並獲取一個輸入字串;如果輸入鍵在對映中可用,則返回其鍵值對,否則返回“未找到”。

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