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
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count(InputIterator first, InputIterator last, const T& value);
Parameters of std::count
| Parameter | Description |
|---|---|
first, last | Input 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. |
value | The 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
#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
- We include the necessary headers:
<iostream>for input/output operations,<vector>for thestd::vectorcontainer, and<algorithm>for thestd::countfunction. - We initialize a vector
numberscontaining a sequence of integers, including multiple occurrences of the value3. - We call
std::count, passing the beginning and end iterators of the vector and the value3to count its occurrences. - The function iterates through the range and counts the number of elements equal to
3. - 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
#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
- We include the necessary headers:
<iostream>for input/output operations,<string>for thestd::stringcontainer, and<algorithm>for thestd::countfunction. - We define a string
textcontaining the sentence “hello world, welcome to C++ programming”. - We call
std::count, passing the beginning and end iterators of the string and the character'o'to count its occurrences. - The function iterates through the string and counts the occurrences of
'o'. - 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
#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
- We define an array
arrcontaining integers, including multiple occurrences of the value20. - We call
std::count, passing the beginning and end of the array usingstd::beginandstd::end, and the value20to count its occurrences. - The function iterates through the array and counts the number of elements equal to
20. - 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
#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
- We define a custom comparator function
faulty_comparatorthat throws astd::runtime_errorif the comparison involves the value-1. - The vector
numberscontains integers, including the value-1. - We use
std::count_ifto count the occurrences of the target value-1. A lambda function wraps the custom comparator. - When
faulty_comparatorencounters the value-1, it throws an exception. - 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
#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
- We define a custom iterator
FaultyIteratorthat throws astd::runtime_errorafter accessing two elements. - An array
arrcontains five elements. - The
std::countfunction uses the custom iterator to iterate through the array and count the occurrences of the value3. - The iterator throws an exception during the third access, which is caught in the
try-catchblock, 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::countfunction 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.
