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


复杂度

平均情况:与计数元素数量成线性关系。
最坏情况:与 容器大小 成线性关系。

迭代器有效性

没有变化。

另见