std::unordered_map<Key,T,Hash,KeyEqual,Allocator>::count
来自 cppreference.cn
< cpp | container | unordered map
size_type count( const Key& key ) const; |
(1) | (C++11 起) |
template< class K > size_type count( const K& x ) const; |
(2) | (C++20 起) |
1) 返回与指定参数 key 相等的键的元素数量,由于此容器不允许重复键,因此结果为 0 或 1。
2) 返回与指定参数 x 等价的键的元素数量。仅当 Hash::is_transparent 和 KeyEqual::is_transparent 有效且各自表示类型时,此重载才参与重载决议。这假定此类
Hash
可使用 K
和 Key
类型调用,并且 KeyEqual
是透明的,这两者共同允许在不构造 Key
实例的情况下调用此函数。目录 |
[编辑] 参数
key | - | 要计数的元素的键值 |
x | - | 可以与键透明比较的任何类型的值 |
[编辑] 返回值
1) 键为 key 的元素数量,结果为 1 或 0。
2) 与 x 等价的键的元素数量。
[编辑] 复杂度
平均为常数时间复杂度,最坏情况为容器大小的线性时间复杂度。
[编辑] 注意
Feature-test 宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_generic_unordered_lookup |
201811L |
(C++20) | 无序关联容器中的异构比较查找,重载 (2) |
[编辑] 示例
运行此代码
#include <iostream> #include <string> #include <unordered_map> int main() { std::unordered_map<int, std::string> dict = { {1, "one"}, {6, "six"}, {3, "three"} }; dict.insert({4, "four"}); dict.insert({5, "five"}); dict.insert({6, "six"}); std::cout << "dict: { "; for (auto const& [key, value] : dict) std::cout << '[' << key << "]=" << value << ' '; std::cout << "}\n\n"; for (int i{1}; i != 8; ++i) std::cout << "dict.count(" << i << ") = " << dict.count(i) << '\n'; }
可能的输出
dict: { [5]=five [4]=four [1]=one [6]=six [3]=three } dict.count(1) = 1 dict.count(2) = 0 dict.count(3) = 1 dict.count(4) = 1 dict.count(5) = 1 dict.count(6) = 1 dict.count(7) = 0
[编辑] 参见
查找具有特定键的元素 (公开成员函数) | |
(C++20) |
检查容器是否包含具有特定键的元素 (公开成员函数) |
返回匹配特定键的元素范围 (公开成员函数) |