std::set<Key,Compare,Allocator>::count
来自 cppreference.cn
size_type count( const Key& key ) const; |
(1) | |
template< class K > size_type count( const K& x ) const; |
(2) | (自 C++14 起) |
返回键与指定参数等价的元素数量。
1) 返回键为 key 的元素数量。由于此容器不允许重复键,因此结果为 1 或 0。
2) 返回键与值 x 等价的元素数量。仅当限定标识符 Compare::is_transparent 有效并表示类型时,此重载才参与重载决议。它允许在不构造
Key
实例的情况下调用此函数。内容 |
[edit] 参数
key | - | 要计数的元素的键值 |
x | - | 与键进行比较的替代值 |
[edit] 返回值
键与 key 或 x 等价 的元素数量,对于重载 (1),结果为 1 或 0。
[edit] 复杂度
容器大小的对数加上找到的元素数量的线性时间。
注解
特性测试 宏 | 值 | Std | 特性 |
---|---|---|---|
__cpp_lib_generic_associative_lookup |
201304L |
(C++14) | 关联容器中的异构比较查找;重载 (2) |
[edit] 示例
运行此代码
#include <functional> #include <iostream> #include <set> struct S { int x; S(int i) : x{i} { std::cout << "S{" << i << "} "; } bool operator<(S const& s) const { return x < s.x; } }; struct R { int x; R(int i) : x{i} { std::cout << "R{" << i << "} "; } bool operator<(R const& r) const { return x < r.x; } }; bool operator<(R const& r, int i) { return r.x < i; } bool operator<(int i, R const& r) { return i < r.x; } int main() { std::set<int> t{3, 1, 4, 1, 5}; std::cout << t.count(1) << ", " << t.count(2) << ".\n"; std::set<S> s{3, 1, 4, 1, 5}; std::cout << ": " << s.count(1) << ", " << s.count(2) << ".\n"; // Two temporary objects S{1} and S{2} were created. // Comparison function object is defaulted std::less<S>, // which is not transparent (has no is_transparent member type). std::set<R, std::less<>> r{3, 1, 4, 1, 5}; std::cout << ": " << r.count(1) << ", " << r.count(2) << ".\n"; // C++14 heterogeneous lookup; temporary objects were not created. // Comparator std::less<void> has predefined is_transparent. }
输出
1, 0. S{3} S{1} S{4} S{1} S{5} : S{1} 1, S{2} 0. R{3} R{1} R{4} R{1} R{5} : 1, 0.
[edit] 参见
查找具有特定键的元素 (公开成员函数) | |
返回与特定键匹配的元素范围 (公开成员函数) |