본문으로 건너뛰기
Previous
Next
C++ Algorithm Count | '카운트 알고리즘' 가이드

C++ Algorithm Count | '카운트 알고리즘' 가이드

C++ Algorithm Count | '카운트 알고리즘' 가이드

이 글의 핵심

C++ std::count와 count_if로 값 일치·조건 만족 요소 개수 세기. all_of, any_of, none_of까지 한 번에 정리한 실전 가이드.

들어가며

카운트 알고리즘은 컨테이너의 요소를 세거나 조건을 검사하는 알고리즘입니다. count, count_if, all_of, any_of, none_of 등을 제공합니다.


코딩 테스트 준비하며 깨달은 것

알고리즘 문제를 풀다 보면 “이게 실무에 무슨 도움이 될까?” 하는 의문이 들 때가 있습니다. 저도 그랬습니다. 하지만 실제 프로젝트에서 성능 문제에 부딪히면, 알고리즘 지식이 얼마나 중요한지 깨닫게 됩니다. 예를 들어, 사용자 검색 기능이 느려서 고민하다가 해시 테이블을 적용하니 응답 시간이 10초에서 0.1초로 줄어든 경험이 있습니다.

코딩 테스트는 단순히 취업을 위한 관문이 아니라, 문제 해결 능력을 키우는 훈련장입니다. 처음엔 브루트 포스로 풀다가, 시간 복잡도를 개선하는 과정에서 “아, 이렇게 생각하면 되는구나” 하는 깨달음을 얻을 때의 쾌감은 말로 표현하기 어렵습니다. 이 글에서는 단순히 정답 코드만 제시하는 게 아니라, 문제를 어떻게 접근하고 최적화하는지 사고 과정을 함께 공유하겠습니다.

1. count

기본 사용

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

int main() {
    std::vector<int> v = {1, 2, 3, 2, 4, 2, 5};
    
    // 2의 개수
    int count = std::count(v.begin(), v.end(), 2);
    
    std::cout << "2의 개수: " << count << std::endl;  // 3
    
    return 0;
}

문자열에서 사용

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

int main() {
    std::string text = "hello world";
    
    // 'l'의 개수
    int count = std::count(text.begin(), text.end(), 'l');
    
    std::cout << "'l'의 개수: " << count << std::endl;  // 3
    
    return 0;
}

2. count_if

조건부 카운트

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // 짝수 개수
    int evenCount = std::count_if(v.begin(), v.end(),  {
        return x % 2 == 0;
    });
    
    std::cout << "짝수 개수: " << evenCount << std::endl;  // 5
    
    // 5보다 큰 수
    int greaterThan5 = std::count_if(v.begin(), v.end(),  {
        return x > 5;
    });
    
    std::cout << "5보다 큰 수: " << greaterThan5 << std::endl;  // 5
    
    return 0;
}

구조체에서 사용

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

struct Student {
    std::string name;
    int score;
};

int main() {
    std::vector<Student> students = {
        {"Alice", 85},
        {"Bob", 92},
        {"Charlie", 78},
        {"David", 95},
        {"Eve", 88}
    };
    
    // 90점 이상
    int highScores = std::count_if(students.begin(), students.end(),
         {
            return s.score >= 90;
        });
    
    std::cout << "90점 이상: " << highScores << "명" << std::endl;  // 2명
    
    return 0;
}

3. all_of, any_of, none_of

all_of (모두)

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

int main() {
    std::vector<int> v1 = {2, 4, 6, 8, 10};
    std::vector<int> v2 = {2, 4, 5, 8, 10};
    
    // 모두 짝수?
    bool allEven1 = std::all_of(v1.begin(), v1.end(),  {
        return x % 2 == 0;
    });
    
    bool allEven2 = std::all_of(v2.begin(), v2.end(),  {
        return x % 2 == 0;
    });
    
    std::cout << "v1 모두 짝수: " << std::boolalpha << allEven1 << std::endl;  // true
    std::cout << "v2 모두 짝수: " << std::boolalpha << allEven2 << std::endl;  // false
    
    return 0;
}

any_of (하나라도)

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

int main() {
    std::vector<int> v1 = {1, 3, 5, 7, 9};
    std::vector<int> v2 = {1, 3, 4, 7, 9};
    
    // 하나라도 짝수?
    bool hasEven1 = std::any_of(v1.begin(), v1.end(),  {
        return x % 2 == 0;
    });
    
    bool hasEven2 = std::any_of(v2.begin(), v2.end(),  {
        return x % 2 == 0;
    });
    
    std::cout << "v1 짝수 있음: " << std::boolalpha << hasEven1 << std::endl;  // false
    std::cout << "v2 짝수 있음: " << std::boolalpha << hasEven2 << std::endl;  // true
    
    return 0;
}

none_of (없음)

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

int main() {
    std::vector<int> v = {1, 3, 5, 7, 9};
    
    // 음수 없음?
    bool noNegative = std::none_of(v.begin(), v.end(),  {
        return x < 0;
    });
    
    std::cout << "음수 없음: " << std::boolalpha << noNegative << std::endl;  // true
    
    return 0;
}

4. 자주 발생하는 문제

문제 1: 빈 범위

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

int main() {
    std::vector<int> empty;
    
    // count: 0
    int count = std::count(empty.begin(), empty.end(), 5);
    std::cout << "count: " << count << std::endl;  // 0
    
    // all_of: true (공허한 참)
    bool all = std::all_of(empty.begin(), empty.end(),  { return x > 0; });
    std::cout << "all_of: " << std::boolalpha << all << std::endl;  // true
    
    // any_of: false
    bool any = std::any_of(empty.begin(), empty.end(),  { return x > 0; });
    std::cout << "any_of: " << std::boolalpha << any << std::endl;  // false
    
    // none_of: true
    bool none = std::none_of(empty.begin(), empty.end(),  { return x < 0; });
    std::cout << "none_of: " << std::boolalpha << none << std::endl;  // true
    
    return 0;
}

문제 2: 반환 타입

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5};
    
    // count 반환 타입: difference_type (보통 ptrdiff_t)
    auto count = std::count(v.begin(), v.end(), 3);
    
    // ✅ 명시적 타입
    size_t count2 = std::count(v.begin(), v.end(), 3);
    
    std::cout << "count: " << count << std::endl;
    std::cout << "count2: " << count2 << std::endl;
    
    return 0;
}

문제 3: 단락 평가

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    int checks = 0;
    
    // any_of: 첫 true에서 중단
    bool hasEven = std::any_of(v.begin(), v.end(), [&checks](int x) {
        ++checks;
        std::cout << "검사: " << x << std::endl;
        return x % 2 == 0;
    });
    
    std::cout << "짝수 있음: " << std::boolalpha << hasEven << std::endl;
    std::cout << "검사 횟수: " << checks << std::endl;  // 2 (1, 2만 검사)
    
    return 0;
}

출력:

검사: 1
검사: 2
짝수 있음: true
검사 횟수: 2

문제 4: 성능

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

int main() {
    std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    // ❌ 여러 번 순회
    int even = std::count_if(v.begin(), v.end(),  { return x % 2 == 0; });
    int odd = std::count_if(v.begin(), v.end(),  { return x % 2 != 0; });
    int gt5 = std::count_if(v.begin(), v.end(),  { return x > 5; });
    
    // ✅ 한 번에 순회
    int evenCount = 0, oddCount = 0, gt5Count = 0;
    for (int x : v) {
        if (x % 2 == 0) ++evenCount;
        else ++oddCount;
        if (x > 5) ++gt5Count;
    }
    
    std::cout << "짝수: " << evenCount << ", 홀수: " << oddCount 
              << ", >5: " << gt5Count << std::endl;
    
    return 0;
}

5. 실전 예제: 통계 유틸리티

#include <algorithm>
#include <vector>
#include <numeric>
#include <cmath>
#include <iostream>

class Statistics {
public:
    // 기본 통계
    static void analyze(const std::vector<int>& data) {
        if (data.empty()) {
            std::cout << "데이터 없음" << std::endl;
            return;
        }
        
        // 개수
        size_t count = data.size();
        
        // 합계
        int sum = std::accumulate(data.begin(), data.end(), 0);
        
        // 평균
        double mean = static_cast<double>(sum) / count;
        
        // 최소/최대
        auto [minIt, maxIt] = std::minmax_element(data.begin(), data.end());
        
        // 짝수/홀수
        int evenCount = std::count_if(data.begin(), data.end(),  {
            return x % 2 == 0;
        });
        int oddCount = count - evenCount;
        
        // 양수/음수/0
        int positive = std::count_if(data.begin(), data.end(),  { return x > 0; });
        int negative = std::count_if(data.begin(), data.end(),  { return x < 0; });
        int zero = std::count(data.begin(), data.end(), 0);
        
        // 출력
        std::cout << "=== 통계 ===" << std::endl;
        std::cout << "개수: " << count << std::endl;
        std::cout << "합계: " << sum << std::endl;
        std::cout << "평균: " << mean << std::endl;
        std::cout << "최소: " << *minIt << std::endl;
        std::cout << "최대: " << *maxIt << std::endl;
        std::cout << "짝수: " << evenCount << ", 홀수: " << oddCount << std::endl;
        std::cout << "양수: " << positive << ", 음수: " << negative << ", 0: " << zero << std::endl;
    }
    
    // 조건 검사
    static void validate(const std::vector<int>& data) {
        // 모두 양수?
        bool allPositive = std::all_of(data.begin(), data.end(),  {
            return x > 0;
        });
        
        // 하나라도 음수?
        bool hasNegative = std::any_of(data.begin(), data.end(),  {
            return x < 0;
        });
        
        // 0 없음?
        bool noZero = std::none_of(data.begin(), data.end(),  {
            return x == 0;
        });
        
        std::cout << "\n=== 검증 ===" << std::endl;
        std::cout << "모두 양수: " << std::boolalpha << allPositive << std::endl;
        std::cout << "음수 있음: " << std::boolalpha << hasNegative << std::endl;
        std::cout << "0 없음: " << std::boolalpha << noZero << std::endl;
    }
    
    // 범위 검사
    static bool inRange(const std::vector<int>& data, int min, int max) {
        return std::all_of(data.begin(), data.end(), [min, max](int x) {
            return x >= min && x <= max;
        });
    }
};

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    
    Statistics::analyze(data);
    Statistics::validate(data);
    
    std::cout << "\n범위 [1, 10]: " << std::boolalpha 
              << Statistics::inRange(data, 1, 10) << std::endl;  // true
    
    std::cout << "범위 [1, 5]: " << std::boolalpha 
              << Statistics::inRange(data, 1, 5) << std::endl;  // false
    
    return 0;
}

출력:

터미널에서 다음 명령어를 실행합니다.

=== 통계 ===
개수: 10
합계: 55
평균: 5.5
최소: 1
최대: 10
짝수: 5, 홀수: 5
양수: 10, 음수: 0, 0: 0

=== 검증 ===
모두 양수: true
음수 있음: false
0 없음: true

범위 [1, 10]: true
범위 [1, 5]: false

6. 카운트 알고리즘 비교

함수 시그니처

#include <algorithm>

// count: 값 개수
template<class InputIt, class T>
typename iterator_traits<InputIt>::difference_type
count(InputIt first, InputIt last, const T& value);

// count_if: 조건 개수
template<class InputIt, class UnaryPredicate>
typename iterator_traits<InputIt>::difference_type
count_if(InputIt first, InputIt last, UnaryPredicate p);

// all_of: 모두 만족?
template<class InputIt, class UnaryPredicate>
bool all_of(InputIt first, InputIt last, UnaryPredicate p);

// any_of: 하나라도 만족?
template<class InputIt, class UnaryPredicate>
bool any_of(InputIt first, InputIt last, UnaryPredicate p);

// none_of: 모두 불만족?
template<class InputIt, class UnaryPredicate>
bool none_of(InputIt first, InputIt last, UnaryPredicate p);

비교 표

알고리즘반환 타입시간복잡도단락 평가빈 범위
countdifference_typeO(n)0
count_ifdifference_typeO(n)0
all_ofboolO(n)true
any_ofboolO(n)false
none_ofboolO(n)true

정리

핵심 요약

  1. count: 특정 값 개수
  2. count_if: 조건 만족 개수
  3. all_of: 모두 만족? (단락 평가)
  4. any_of: 하나라도 만족? (단락 평가)
  5. none_of: 모두 불만족? (단락 평가)
  6. 시간복잡도: 모두 O(n)

카운트 알고리즘 선택 가이드

목적알고리즘예시
특정 값 개수countcount(v.begin(), v.end(), 5)
조건 만족 개수count_ifcount_if(v.begin(), v.end(), isEven)
모두 만족?all_ofall_of(v.begin(), v.end(), isPositive)
하나라도 만족?any_ofany_of(v.begin(), v.end(), isNegative)
모두 불만족?none_ofnone_of(v.begin(), v.end(), isZero)

실전 팁

사용 원칙:

  • 특정 값 개수는 count
  • 조건부 개수는 count_if
  • 검증은 all_of, any_of, none_of
  • 단락 평가 활용 (성능)

성능:

  • 모두 O(n) 순회
  • any_of, all_of는 단락 평가 (조기 종료)
  • 여러 조건은 한 번에 순회
  • 빈 범위 체크

주의사항:

  • 빈 범위: all_of는 true, any_of는 false
  • 반환 타입: countdifference_type
  • 단락 평가: any_of는 첫 true에서 중단
  • 부작용 금지: predicate는 순수 함수

다음 단계


관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ Algorithm Count | ‘카운트 알고리즘’ 가이드」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ Algorithm Count | ‘카운트 알고리즘’ 가이드」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.


자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. C++ std::count와 count_if로 값 일치·조건 만족 요소 개수 세기. all_of, any_of, none_of까지 한 번에 정리한 실전 가이드. C++·알고리즘·count 중심으로 설명합니다. Sta… 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.


같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, 알고리즘, count, predicate, STL 등으로 검색하시면 이 글이 도움이 됩니다.