C++ <algorithm> std::count

The std::count function in C++ is part of the <algorithm> header and is used to count the number of occurrences of a specific value within a range. It operates on a range defined by two iterators and returns the count of elements equal to the specified value.


Syntax of std::count

</>
Copy
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count(InputIterator first, InputIterator last, const T& value);

Parameters of std::count

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.
valueThe value to count within the range.

Return Value of std::count

The function returns the number of elements in the range [first, last) that are equal to value. The return type is a signed integral type, specifically std::iterator_traits<InputIterator>::difference_type.


Examples for count

Example 1: Counting Occurrences of an Integer

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

Program

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

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

    int count_3 = std::count(numbers.begin(), numbers.end(), 3);

    std::cout << "The number 3 appears " << count_3 << " times in the vector." << std::endl;

    return 0;
}

Output

The number 3 appears 3 times in the vector.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, and <algorithm> for the std::count function.
  2. We initialize a vector numbers containing a sequence of integers, including multiple occurrences of the value 3.
  3. We call std::count, passing the beginning and end iterators of the vector and the value 3 to count its occurrences.
  4. The function iterates through the range and counts the number of elements equal to 3.
  5. The result is stored in count_3, which is then printed to the console.

Example 2: Counting Characters in a String

In this example, we use std::count to count the occurrences of a specific character in a string.

Program

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

int main() {
    std::string text = "hello world, welcome to C++ programming";

    char target = 'o';
    int count_o = std::count(text.begin(), text.end(), target);

    std::cout << "The character 'o' appears " << count_o << " times in the string." << std::endl;

    return 0;
}

Output

The character 'o' appears 5 times in the string.

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <string> for the std::string container, and <algorithm> for the std::count function.
  2. We define a string text containing the sentence “hello world, welcome to C++ programming”.
  3. We call std::count, passing the beginning and end iterators of the string and the character 'o' to count its occurrences.
  4. The function iterates through the string and counts the occurrences of 'o'.
  5. The result is stored in count_o, which is then printed to the console.

Example 3: Counting Elements in an Array

In this example, we use std::count to count the occurrences of a specific element in an array.

Program

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

int main() {
    int arr[] = {10, 20, 30, 20, 40, 50, 20};

    int count_20 = std::count(std::begin(arr), std::end(arr), 20);

    std::cout << "The number 20 appears " << count_20 << " times in the array." << std::endl;

    return 0;
}

Output

The number 20 appears 3 times in the array.

Explanation

  1. We define an array arr containing integers, including multiple occurrences of the value 20.
  2. We call std::count, passing the beginning and end of the array using std::begin and std::end, and the value 20 to count its occurrences.
  3. The function iterates through the array and counts the number of elements equal to 20.
  4. The result is stored in count_20, which is then printed to the console.

Examples for Exceptions Thrown by std::count

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

  • If an element comparison throws an exception.
  • If an operation on iterators, such as dereferencing or incrementing, throws an exception.

Example 1: Element Comparison Throws an Exception

This example demonstrates a case where the element comparison operation throws an exception during execution.

Program

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

bool faulty_comparator(int element, int target) {
    if (element == -1 || target == -1) {
        throw std::runtime_error("Comparison with -1 is not allowed.");
    }
    return element == target;
}

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

    try {
        // Using a lambda to pass the custom comparator
        int count = std::count_if(numbers.begin(), numbers.end(),
                                  [&target](int element) {
                                      return faulty_comparator(element, target);
                                  });

        std::cout << "The number " << target << " appears " << count << " times." << std::endl;
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Comparison with -1 is not allowed.

Explanation

  1. We define a custom comparator function faulty_comparator that throws a std::runtime_error if the comparison involves the value -1.
  2. The vector numbers contains integers, including the value -1.
  3. We use std::count_if to count the occurrences of the target value -1. A lambda function wraps the custom comparator.
  4. When faulty_comparator encounters the value -1, it throws an exception.
  5. The exception is caught in the try-catch block, and an error message is printed.

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 target = 3;
        int count = std::count(FaultyIterator(arr, true), FaultyIterator(arr + 5), target);
        std::cout << "The number " << target << " appears " << count << " times." << 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 function uses the custom iterator to iterate through the array and count the occurrences of the value 3.
  4. The iterator throws an exception during the third access, which is caught in the try-catch block, and an error message is printed.

Complexity

The time complexity of std::count is linear, performing exactly last - first comparisons, where last and first are the iterators defining the range.


Key Points

  • The std::count function is a simple and efficient way to count occurrences of a value in a container.
  • It works on any container that provides input iterators, including arrays, vectors, and strings.
  • It does not modify the container.
  • Invalid arguments, such as mismatched iterators, lead to undefined behavior.