std::set<Key,Compare,Allocator>::count
来自cppreference.com
size_type count( const Key& key ) const; |
(1) | (C++26 起为 constexpr) |
template< class K > size_type count( const K& x ) const; |
(2) | (C++14 起) (C++26 起为 constexpr) |
返回拥有与指定实参比较等价的键的元素数。
1) 返回拥有键 key 的元素数。,因为此容器不允许重复,故只能为 1 或 0。
2) 返回拥有比较等价于 x 的键的元素数。
目录 |
[编辑] 参数
key | - | 要计量元素数的键值 |
x | - | 要与键比较的替用值 |
[编辑] 返回值
拥有比较等价于 key 或 x 的键的元素数。
[编辑] 复杂度
与容器大小成对数,加上与找到的元素数成线性。
注解
功能特性测试宏 | 值 | 标准 | 功能特性 |
---|---|---|---|
__cpp_lib_generic_associative_lookup |
201304L |
(C++14) | 关联容器中的异质比较查找;重载 (2) |
[编辑] 示例
运行此代码
#include <functional> #include <iostream> #include <set> struct S { int x; S(int i) : x{i} { std::cout << "S{" << i << "} "; } bool operator<(const S& s) const { return x < s.x; } }; struct R { int x; R(int i) : x{i} { std::cout << "R{" << i << "} "; } bool operator<(const R& r) const { return x < r.x; } }; bool operator<(const R& r, int i) { return r.x < i; } bool operator<(int i, const R& 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"; // 创建了两个临时对象 S{1} 和 S{2}。 // 比较函数对象默认为 std::less<S>, // 它不透明(没有 is_transparent 嵌套类型)。 std::set<R, std::less<>> r{3, 1, 4, 1, 5}; std::cout << ": " << r.count(1) << ", " << r.count(2) << ".\n"; // C++14 异质查找;不会创建临时对象。 // 比较器 std::less<void> 预定义了 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.
[编辑] 参阅
寻找带有特定键的元素 (公开成员函数) | |
返回匹配特定键的元素范围 (公开成员函数) |