Namespaces
Variants

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

From cppreference.net

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 比较等价元素的数量。
此重载仅当 Compare 满足 透明性 时参与重载决议。它允许在不构造 Key 实例的情况下调用此函数。

目录

参数

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 R& 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.

参见

查找具有特定键的元素
(公开成员函数)
返回匹配特定键的元素范围
(公开成员函数)