💡 퀵 접속: cpp.kr/count

count

C++ 표준 라이브러리의 알고리즘으로, 주어진 범위에서 특정 값과 일치하는 요소의 개수를 반환합니다. 기본적으로 == 연산자를 사용하여 비교합니다.

기본 사용법

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> numbers = {1, 2, 3, 2, 4, 2, 5, 6, 2, 7};
    
    // 값이 2인 요소의 개수 세기
    int count = std::count(numbers.begin(), numbers.end(), 2);
    
    std::cout << "값이 2인 요소의 개수: " << count << std::endl;
    
    // 값이 8인 요소의 개수 세기
    count = std::count(numbers.begin(), numbers.end(), 8);
    std::cout << "값이 8인 요소의 개수: " << count << std::endl;
    
    return 0;
}

실행 결과:

값이 2인 요소의 개수: 4
값이 8인 요소의 개수: 0

문자열에서 사용

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string text = "Hello, World!";
    
    // 문자 'l'의 개수 세기
    int count = std::count(text.begin(), text.end(), 'l');
    std::cout << "문자 'l'의 개수: " << count << std::endl;
    
    // 문자 'o'의 개수 세기
    count = std::count(text.begin(), text.end(), 'o');
    std::cout << "문자 'o'의 개수: " << count << std::endl;
    
    return 0;
}

실행 결과:

문자 'l'의 개수: 3
문자 'o'의 개수: 2

사용자 정의 타입에서 사용

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

struct Person {
    std::string name;
    int age;
    
    bool operator==(const Person& other) const {
        return name == other.name && age == other.age;
    }
};

int main() {
    std::vector<Person> people = {
        {"Alice", 20},
        {"Bob", 25},
        {"Alice", 20},
        {"Charlie", 30},
        {"Alice", 20},
        {"David", 35}
    };
    
    Person target = {"Alice", 20};
    
    // target과 일치하는 요소의 개수 세기
    int count = std::count(people.begin(), people.end(), target);
    
    std::cout << "target과 일치하는 요소의 개수: " << count << std::endl;
    
    return 0;
}

실행 결과:

target과 일치하는 요소의 개수: 3

참고사항

  • count는 algorithm 헤더에 정의되어 있습니다.
  • 기본적으로 == 연산자를 사용하여 비교합니다.
  • 시간 복잡도는 O(n)입니다.
  • 범위가 비어있으면 0을 반환합니다.
  • 요소의 개수를 세는 데 유용합니다.
  • count_if와 함께 사용하여 조건에 맞는 요소의 개수를 셀 수 있습니다.
  • 반환 타입은 반복자의 차이 타입입니다 (일반적으로 std::ptrdiff_t).
함수 설명
count(first, last, value) 주어진 범위에서 value와 일치하는 요소의 개수를 반환