public member function
<unordered_map>

std::unordered_map::count

size_type count ( const key_type& k ) const;
計算具有特定鍵的元素
Searches the container for elements whose key is k and returns the number of elements found. Because unordered_map containers do not allow for duplicate keys, this means that the function actually returns1if an element with that key exists in the container, and zero otherwise.

引數

k
Key value to be searched for.
成員型別key_type是容器中元素的鍵的型別,在 unordered_map 中定義為其第一個模板引數的別名().

返回值

1if an element with a key equivalent to k is found, or zero otherwise.

成員型別size_type是一種無符號整型型別。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// unordered_map::count
#include <iostream>
#include <string>
#include <unordered_map>

int main ()
{
  std::unordered_map<std::string,double> mymap = {
     {"Burger",2.99},
     {"Fries",1.99},
     {"Soda",1.50} };

  for (auto& x: {"Burger","Pizza","Salad","Soda"}) {
    if (mymap.count(x)>0)
      std::cout << "mymap has " << x << std::endl;
    else
      std::cout << "mymap has no " << x << std::endl;
  }

  return 0;
}

輸出
mymap has Burger
mymap has no Pizza
mymap has no Salad
mymap has Soda


複雜度

平均情況:與計數元素數量成線性關係。
最壞情況:與 容器大小 成線性關係。

迭代器有效性

沒有變化。

另見