C++ <algorithm> std::count_if

The std::count_if function in C++ is part of the <algorithm> header and is used to count the number of elements in a range that satisfy a specific condition, defined by a unary predicate.


Syntax of std::count_if

</>
Copy
template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
count_if(InputIterator first, InputIterator last, UnaryPredicate pred);

Parameters of std::count_if

ParameterDescription
first, lastInput iterators defining the range to examine. The range is [first, last), including all elements between first and last, excluding the element pointed to by last.
predUnary function that accepts an element in the range as an argument and returns a value convertible to bool. The value returned indicates whether the element is counted by this function. The function shall not modify its argument. This can either be a function pointer or a function object.

Return Value of std::count_if

The function returns the number of elements in the range [first, last) for which pred does not return false. The return type is a signed integral type, specifically std::iterator_traits<InputIterator>::difference_type.


Examples for count_if

Example 1: Counting Odd Numbers in a Vector

In this example, we use std::count_if to count the number of odd integers in a vector.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>

bool isOdd(int i) {
    return (i % 2) == 1;
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

    int odd_count = std::count_if(numbers.begin(), numbers.end(), isOdd);

    std::cout << "The vector contains " << odd_count << " odd numbers." << std::endl;

    return 0;
}

Output

The vector contains 5 odd numbers.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, and <algorithm> for the std::count_if function.
  2. We define a function isOdd that returns true if a number is odd and false otherwise.
  3. We initialize a vector numbers containing integers from 1 to 9.
  4. We call std::count_if, passing the beginning and end iterators of the vector and the isOdd function as the predicate to count the number of odd integers.
  5. The result is stored in odd_count, which is then printed to the console.

Example 2: Counting Words Longer Than Four Characters

In this example, we use std::count_if to count the number of words in a vector that have more than four characters.

Program

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

bool isLongerThanFour(const std::string& word) {
    return word.length() > 4;
}

int main() {
    std::vector<std::string> words = {"apple", "banana", "kiwi", "grape", "orange"};

    int long_word_count = std::count_if(words.begin(), words.end(), isLongerThanFour);

    std::cout << "There are " << long_word_count << " words longer than four characters." << std::endl;

    return 0;
}

Output

There are 4 words longer than four characters.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, <string> for the std::string class, and <algorithm> for the std::count_if function.
  2. We define a function isLongerThanFour that returns true if a word has more than four characters.
  3. We initialize a vector words containing a list of fruit names.
  4. We call std::count_if, passing the beginning and end iterators of the vector and the isLongerThanFour function as the predicate to count the number of words longer than four characters.
  5. The result is stored in long_word_count, which is then printed to the console.

Example 3: Counting Positive Numbers in an Array

In this example, we use std::count_if to count the number of positive integers in an array.

Program

</>
Copy
#include <iostream>
#include <algorithm>

int main() {
    int numbers[] = {-1, 2, -3, 4, -5, 6, 0};

    // Count positive numbers using a lambda function
    int positive_count = std::count_if(std::begin(numbers), std::end(numbers), [](int n) {
        return n > 0;
    });

    std::cout << "The array contains " << positive_count << " positive numbers." << std::endl;

    return 0;
}

Output

The array contains 3 positive numbers.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations and <algorithm> for the std::count_if function.
  2. We define an array numbers containing a mix of positive, negative, and zero values.
  3. We use std::count_if, passing the beginning and end of the array and a lambda function as the predicate. The lambda function checks if a number is greater than zero.
  4. The function iterates through the array and counts the number of elements that satisfy the condition n > 0.
  5. The result is stored in positive_count, which is then printed to the console.

Examples for Exceptions Thrown by std::count_if

The std::count_if function can throw exceptions in the following scenarios:

  • If the predicate function (pred) throws an exception.
  • If an operation on the iterators, such as dereferencing or incrementing, throws an exception.

Example 1: Predicate Throws an Exception

This example demonstrates a case where the predicate function throws an exception during execution.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

bool faulty_predicate(int n) {
    if (n < 0) {
        throw std::runtime_error("Negative numbers are not allowed.");
    }
    return n % 2 == 0;
}

int main() {
    std::vector<int> numbers = {1, 2, -3, 4, 5, -6};

    try {
        int even_count = std::count_if(numbers.begin(), numbers.end(), faulty_predicate);
        std::cout << "The vector contains " << even_count << " even numbers." << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Negative numbers are not allowed.

Explanation

  1. We define a predicate function faulty_predicate that throws a std::runtime_error if the input is a negative number.
  2. The vector numbers contains integers, including negative values.
  3. The std::count_if function applies the predicate to each element in the vector. When it encounters a negative number, the predicate throws an exception.
  4. The exception is caught in the try-catch block, and an error message is displayed.

Example 2: Iterator Throws an Exception

This example demonstrates a case where a custom iterator throws an exception during iteration.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

class FaultyIterator {
public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = int;
    using difference_type = std::ptrdiff_t;
    using pointer = const int*;
    using reference = const int&;

    FaultyIterator(const int* ptr, bool fail_after = false)
        : ptr(ptr), fail_after(fail_after), count(0) {}

    reference operator*() const {
        if (fail_after && count >= 2) {
            throw std::runtime_error("Iterator error during dereference.");
        }
        return *ptr;
    }

    FaultyIterator& operator++() {
        ++ptr;
        ++count;
        return *this;
    }

    bool operator!=(const FaultyIterator& other) const {
        return ptr != other.ptr;
    }

private:
    const int* ptr;
    bool fail_after;
    int count;
};

int main() {
    int arr[] = {1, 2, 3, 4, 5};

    try {
        int count = std::count_if(
            FaultyIterator(arr, true),
            FaultyIterator(arr + 5),
            [](int n) { return n % 2 == 0; }
        );

        std::cout << "The array contains " << count << " even numbers." << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Iterator error during dereference.

Explanation

  1. We define a custom iterator FaultyIterator that throws a std::runtime_error after accessing two elements.
  2. An array arr contains five elements.
  3. The std::count_if function uses the custom iterator to iterate through the array and count the even numbers using a lambda function as the predicate.
  4. The iterator throws an exception during the third access, which is caught in the try-catch block, and an error message is displayed.