std::unordered_set count() 方法
- 自 C++20 起
- 自 C++11 起
// (1) Const version only
size_type count( const Key& key ) const;
// (2) Const version only
template< class K >
size_type count( const K& x ) const;
// (1) Const version only
size_type count( 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 <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 << ' ';
}
}
}
可能输出
The set is: 8 1 7 2
Numbers from 1 to 8 that are in the set: 1 2 7 8