std::unordered_set<Key,Hash,KeyEqual,Allocator>::count
来自cppreference.com
<tbody>
</tbody>
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 比较相等的键的元素数,因为此容器不允许重复故为 1 或 0。2) 返回拥有比较等价于指定实参
x 的键的元素数。此重载只有在Hash::is_transparent 与 KeyEqual::is_transparent 均合法并指代类型时才会参与重载决议。这假设使得 Hash 能用 K 和 Key 类型调用,并且 KeyEqual 是透明的,进而允许调用此函数时不需要构造 Key 的实例。参数
| key | - | 要计量等价元素数的键值 |
| x | - | 能通透地与键比较的任何类型值 |
返回值
1) 拥有键
key 的元素数,即 1 或 0。2) 键等价于
x 的元素数。复杂度
平均为常数,最坏情况与容器大小成线性。
注解
| 功能特性测试宏 | 值 | 标准 | 功能特性 |
|---|---|---|---|
__cpp_lib_generic_unordered_lookup |
201811L |
(C++20) | Heterogeneous comparison lookup in unordered associative containers, overload (2) |
示例
运行此代码
#include <algorithm>
#include <iostream>
#include <unordered_set>
int main()
{
std::unordered_set set{2, 7, 1, 8, 2, 8, 1, 8, 2, 8};
std::cout << "The set is: ";
for (int e : set)
std::cout << e << ' ';
const auto [min, max] = std::ranges::minmax(set);
std::cout << "\nNumbers from " << min << " to " << max << " that are in the set: ";
for (int i{min}; i <= max; ++i)
if (set.count(i) == 1)
std::cout << i << ' ';
std::cout << '\n';
}
可能的输出:
The set is: 8 1 7 2
Numbers from 1 to 8 that are in the set: 1 2 7 8
参阅
| 寻找带有特定键的元素 (公开成员函数) | |
(C++20) |
检查容器是否含有带特定键的元素 (公开成员函数) |
| 返回匹配特定键的元素范围 (公开成员函数) |