C++ unordered_map::count() 函式



C++ 的unordered_map::count()函式用於返回與鍵關聯的對映值的個數k。這意味著此函式僅給出 1 或 0 的值,因為容器不允許重複鍵,如果容器中存在具有該鍵的元素,則返回 1,否則返回 0。

換句話說,此容器不允許重複值,因此 count() 函式始終返回 0 或 1。

語法

以下是 unordered_map::count() 函式的語法

size_type count(const key_type& k) const;

引數

  • k - 它表示需要在 unordered_map 中返回的計數。

返回值

如果容器具有與鍵 k 關聯的值,則返回 1,否則返回 0。

示例 1

在以下示例中,讓我們看一下 unordered_map::count() 函式的基本用法,如下所示

#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}
   };
   if (um.count('a') == 1) {
      cout << "um['a'] = " << um.at('a') << endl;
   }
   if (um.count('z') == 0) {
      cout << "Value not present for key um['z']" << endl;
   }
   return 0;
}

輸出

以下是上述程式碼的輸出:

um['a'] = 1
Value not present for key um['z']

示例 2

考慮以下示例,我們使用 unordered_map::count() 函式來查詢指定的鍵是否存在,如下所示

#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}
   };
   int count1 = um.count('b');
   cout<<"the count value of b is: "<<count1<<endl;
   int count2 = um.count('z');
   cout<<"the count value of z is: "<<count2;
   return 0;
}

輸出

上述程式碼的輸出如下:

the count value of b is: 1
the count value of z is: 0

示例 3

讓我們看一下以下示例,我們將在 if 條件中使用 unordered_map::count() 函式來顯示與鍵關聯的值k,如下所示

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main () {
   unordered_map<int, string> Umap;
   Umap[1] = "tutorialspoint";
   Umap[2] = "Hyderabad India";
   Umap[3] = "Tutorix";
   Umap[4] = "Noida India";
   if(Umap.count(1)==1 && Umap.count(2)==1){
      cout<<Umap.at(1)<<" "<<Umap.at(2)<<endl;
   }
   return 0;
}

輸出

如果我們執行上述程式碼,它將生成以下輸出:

tutorialspoint Hyderabad India
廣告