Namespaces
Variants

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

From cppreference.net

size_type count ( const Key & key ) const ;
(1) (constexpr since C++26)
template < class K >
size_type count ( const K & x ) const ;
(2) (C++14부터)
(C++26부터 constexpr)

지정된 인자와 비교하여 동등한 키를 가진 요소의 개수를 반환합니다.

1) key 를 가진 요소의 개수를 반환합니다. 키는 항상 고유하므로 이 값은 1 또는 0 입니다.
2) x 와 비교하여 동등한 키를 가진 요소들의 개수를 반환합니다.
이 오버로드는 Compare transparent 인 경우에만 오버로드 해결에 참여합니다. 이를 통해 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.

참고 항목

특정 키를 가진 요소를 찾습니다
(public member function)
특정 키와 일치하는 요소들의 범위를 반환합니다
(public member function)