std::unordered_map count() 方法
- 自 C++20 起
- 自 C++11 起
// (1) Non const version
iterator find( const Key& key );
// (2) Const version
const_iterator find( const Key& key ) const;
// (3) Non const version
template< class K > iterator find( const K& x );
// (4) Const version
template< class K > const_iterator find( const K& x ) const;
// (1) Non const version
iterator find( const Key& key );
// (2) Const version
const_iterator find( const Key& key ) const;
- (1) 返回键与指定参数
key
相等(比较)的元素数量,由于此容器不允许重复,所以其值为 1 或 0。 - (2) 返回具有与指定参数
x
比较等效的键的元素的数量。此重载仅在Hash::is_transparent
和KeyEqual::is_transparent
有效且分别表示一个类型时参与重载解析。这假定这样的Hash
可以同时用K
和Key
类型调用,并且KeyEqual
是透明的,两者结合起来,允许在不构造Key
实例的情况下调用此函数。
参数
key
- 要计数的元素的键值x
- 可以与键透明比较的任何类型的值
返回值
- (1) 键为
key
的元素数量,即 1 或 0。 - (2) 键与
x
等效的元素数量。
复杂度
平均情况,常数 - O(1)。
最坏情况,与容器大小呈线性关系 - O(size())。
异常
(无)
备注
特性测试宏: __cpp_lib_generic_unordered_lookup
(用于重载 (2))
示例
Main.cpp
#include <string>
#include <iostream>
#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