命名空间
变体
操作

std::set<Key,Compare,Allocator>::count

来自 cppreference.cn
< cpp‎ | 容器‎ | set
 
 
 
 
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 比较等价的键的元素数量。此重载仅在限定 ID Compare::is_transparent 有效并表示一个类型时才参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

目录

[编辑] 参数

key - 要计数的元素的键值
x - 与键比较的备用值

[编辑] 返回值

键与 keyx 比较等价的元素数量,对于重载 (1),该数量为 1 或 0。

[编辑] 复杂度

对容器大小呈对数复杂度,加上对找到的元素数量呈线性复杂度。

注意

特性测试 标准 特性
__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<(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.

[编辑] 参阅

查找具有特定键的元素
(public member function) [edit]
返回与特定键匹配的元素范围
(public member function) [edit]