std::unordered_set<Key,Hash,KeyEqual,Allocator>::count
来自 cppreference.cn
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 比较等价的键的元素的数量。
[编辑] 复杂度
平均情况下为常数时间,最坏情况下与容器大小成线性关系。
[编辑] 注意
特性测试宏 | 值 | 标准 | 特性 |
---|---|---|---|
__cpp_lib_generic_unordered_lookup |
201811L |
(C++20) | 无序关联容器中的异构比较查找,重载 (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) |
检查容器是否包含具有特定键的元素 (公共成员函数) |
返回与特定键匹配的元素范围 (公共成员函数) |