💡 퀵 접속: cpp.kr/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(first, last, value) | 주어진 범위에서 value와 일치하는 요소의 개수를 반환 |