C++ Algorithm Count | "Count Algorithm" Guide

C++ Algorithm Count | "Count Algorithm" Guide

이 글의 핵심

std::count, count_if, all_of, any_of, none_of—linear scans and short-circuit predicates for validation and analytics in C++.

The <algorithm> counting utilities let you answer how many values match a value or predicate, and whether all / any / none of the elements satisfy a condition—without writing error-prone manual loops. Complexity is linear in the range size: count / count_if scan once; all_of / any_of / none_of can short-circuit (any_of stops at the first true, all_of at the first false).

Count Algorithm

std::count returns the number of elements equal to a given value (using ==). For custom criteria, use std::count_if with a predicate (e.g. lambda).

#include <algorithm>
#include <vector>

std::vector<int> v = {1, 2, 3, 2, 4, 2, 5};

// Count occurrences of 2
int count = std::count(v.begin(), v.end(), 2);
std::cout << "Count of 2: " << count << std::endl;  // 3

Basic usage

Combine count for equality checks and count_if for arbitrary predicates. These work on any forward iterator range; for large data, consider whether a single pass with a hand-written loop could fuse multiple counts—otherwise these functions are clear and correct.

#include <algorithm>

std::vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

// Count specific value
int count = std::count(v.begin(), v.end(), 5);

// Count based on condition
int evenCount = std::count_if(v.begin(), v.end(),
    [](int x) { return x % 2 == 0; });

std::cout << "Even numbers: " << evenCount << std::endl;  // 5

Practical Examples

Example 1: count_if

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> scores = {85, 90, 78, 92, 88, 95, 72};
    
    // Scores 90 and above
    int highScores = std::count_if(scores.begin(), scores.end(),
        [](int score) { return score >= 90; });
    
    std::cout << "Scores 90 and above: " << highScores << std::endl;  // 3
}

Example 2: all_of

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> v = {2, 4, 6, 8, 10};
    
    // Are all elements even?
    bool allEven = std::all_of(v.begin(), v.end(),
        [](int x) { return x % 2 == 0; });
    
    std::cout << "All even: " << allEven << std::endl;  // true
}

Example 3: any_of

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> v = {1, 3, 5, 7, 9};
    
    // Is there at least one even number?
    bool hasEven = std::any_of(v.begin(), v.end(),
        [](int x) { return x % 2 == 0; });
    
    std::cout << "Has even number: " << hasEven << std::endl;  // false
}

Example 4: none_of

#include <algorithm>
#include <vector>

int main() {
    std::vector<int> v = {1, 3, 5, 7, 9};
    
    // Are there no negative numbers?
    bool noNegative = std::none_of(v.begin(), v.end(),
        [](int x) { return x < 0; });
    
    std::cout << "No negative numbers: " << noNegative << std::endl;  // true
}

Conditional Algorithms

// Count
std::count(begin, end, value)
std::count_if(begin, end, pred)

// Condition checks
std::all_of(begin, end, pred)   // All elements satisfy
std::any_of(begin, end, pred)   // At least one satisfies
std::none_of(begin, end, pred)  // None satisfy

Common Issues

Issue 1: Empty Range

std::vector<int> v;

// Empty range
int count = std::count(v.begin(), v.end(), 5);  // 0

// all_of: true (vacuous truth)
bool all = std::all_of(v.begin(), v.end(), pred);  // true

// any_of: false
bool any = std::any_of(v.begin(), v.end(), pred);  // false

// none_of: true
bool none = std::none_of(v.begin(), v.end(), pred);  // true

Issue 2: Type

std::vector<int> v = {1, 2, 3, 4, 5};

// Return type of count
auto count = std::count(v.begin(), v.end(), 3);
// std::iterator_traits<>::difference_type (usually ptrdiff_t)

// ✅ Explicit type
size_t count2 = std::count(v.begin(), v.end(), 3);

Issue 3: Performance

// count: O(n)
int count = std::count(v.begin(), v.end(), value);

// Check multiple conditions at once
int result = std::count_if(v.begin(), v.end(), [](int x) {
    return x == 2 || x == 4 || x == 6;
});

Issue 4: Short-Circuit Evaluation

// any_of: stops at the first true
bool hasEven = std::any_of(v.begin(), v.end(),
    [](int x) { return x % 2 == 0; });

// all_of: stops at the first false
bool allPositive = std::all_of(v.begin(), v.end(),
    [](int x) { return x > 0; });

// Efficient

Usage Patterns

// 1. Count
int count = std::count_if(v.begin(), v.end(), pred);

// 2. Check all
bool all = std::all_of(v.begin(), v.end(), pred);

// 3. Check any
bool any = std::any_of(v.begin(), v.end(), pred);

// 4. Check none
bool none = std::none_of(v.begin(), v.end(), pred);

// 5. Min/Max
auto [minIt, maxIt] = std::minmax_element(v.begin(), v.end());

FAQ

Q1: What is count?

A: Counts the number of occurrences of a value.

Q2: What is count_if?

A: Counts the number of elements that satisfy a condition.

Q3: What is all_of?

A: Checks if all elements satisfy a condition.

Q4: What is any_of?

A: Checks if at least one element satisfies a condition.

Q5: What is none_of?

A: Checks if no elements satisfy a condition.

Q6: Any learning resources?

A:

  • “Effective STL”
  • “C++ Primer”
  • cppreference.com

Here are other posts related to this topic:

  • C++ STL algorithms — English series hub
  • C++ Algorithm Generate | “Generate Algorithm” Guide
  • C++ Algorithm Reverse | “Reverse Algorithm” Guide
  • C++ Algorithm Replace | “Replace Algorithm” Guide

Practical Tips

Tips you can apply directly in real-world scenarios.

Debugging Tips

  • Check compiler warnings first when issues arise.
  • Reproduce problems with simple test cases.

Performance Tips

  • Avoid optimizing without profiling.
  • Set measurable performance goals first.

Code Review Tips

  • Check for commonly flagged issues during code reviews.
  • Follow your team’s coding conventions.

Practical Checklist

Things to check when applying these concepts in real-world projects.

Before Writing Code

  • Is this approach the best solution for the problem?
  • Can your team understand and maintain this code?
  • Does it meet performance requirements?

While Writing Code

  • Have you resolved all compiler warnings?
  • Have you considered edge cases?
  • Is error handling appropriate?

During Code Review

  • Is the intent of the code clear?
  • Are there sufficient test cases?
  • Is the documentation adequate?

Use this checklist to reduce mistakes and improve code quality.


Keywords Covered in This Post (Related Search Terms)

Search for terms like C++, algorithm, count, predicate, STL to find more helpful resources.