std::count,std::count_if(3)
πΈ NAME πΈ
Okay bestie, this is std::count,std::count_if(3), straight from the C++ Standard Libary β and yes, the header spells it βLibary,β weβre keeping that, itβs iconic. The NAME line is literally std::count,std::count_if β std::count,std::count_if, and the whole page is giving βhow many things match?β main character energy. π
β¨ Synopsis β¨
Defined in header <algorithm>.
Defined in header <algorithm>
template< class InputIt, class T >
constexpr typename std::iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T& value );
(1) (constexpr since C++20) (until C++26)
template< class InputIt, class T = typename std::iterator_traits<InputIt>::value_type >
constexpr typename std::iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T& value );
(1) (since C++26)
template< class ExecutionPolicy, class ForwardIt, class T >
typename std::iterator_traits<ForwardIt>::difference_type
count( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, const T& value );
(2) (since C++17) (until C++26)
template< class ExecutionPolicy, class ForwardIt, class T = typename std::iterator_traits<ForwardIt>::value_type >
typename std::iterator_traits<ForwardIt>::difference_type
count( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, const T& value );
(2) (since C++26)
template< class InputIt, class UnaryPred >
constexpr typename std::iterator_traits<InputIt>::difference_type
count_if( InputIt first, InputIt last, UnaryPred p );
(3) (since C++20)
template< class ExecutionPolicy, class ForwardIt, class UnaryPred >
typename std::iterator_traits<ForwardIt>::difference_type
count_if( ExecutionPolicy&& policy,
ForwardIt first, ForwardIt last, UnaryPred p );
(4) (since C++17)
So basically: returns the number of elements in the range [first, last) satisfying specific criteria. Obsessed.
- Counts the elements that are equal to
value(usingoperator==). - Counts elements for which predicate
preturnstrue. - Same as (1,3), but executed according to
policy. These overloads participate in overload resolution only ifstd::is_execution_policy_v<std::decay_t<ExecutionPolicy>>istrue. (until C++20)std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>>istrue. (since C++20)
Wait, bestie, the numbering in the original is a little feral: the description says1)equalsvalue,3)usesp, and2,4)are the policy versions of1,3). Weβre keeping it exactly like that. No cap. π«Ά
π Parameters π
first,lastβ the range of elements to examine.valueβ the value to search for.policyβ the execution policy to use. See execution policy for details.pβ unary predicate which returnstruefor the required elements. The expressionp(v)must be convertible toboolfor every argumentvof type (possibly const)VT, whereVTis the value type ofInputIt, regardless of value category, and must not modifyv. Thus, a parameter type ofVT&is not allowed, nor isVTunless forVTa move is equivalent to a copy (since C++11).
π¦ Type requirements π¦
InputItmust meet the requirements ofLegacyInputIterator.ForwardItmust meet the requirements ofLegacyForwardIterator.UnaryPredmust meet the requirements ofPredicate.
π Return value π
The number of iterators it in the range [first, last) satisfying the following condition:
- 1,2)
*it == valueis true. - 3,4)
p(*it) != falseis true.
π₯ Complexity π₯
Given N as std::distance(first, last):
- 1,2) Exactly
Ncomparisons withvalueusingoperator==. - 3,4) Exactly
Napplications of the predicatep.
π«Ά Exceptions π«Ά
The overloads with a template parameter named ExecutionPolicy report errors as follows:
- If execution of a function invoked as part of the algorithm throws an exception and
ExecutionPolicyis one of the standard policies,std::terminateis called. For any otherExecutionPolicy, the behavior is implementation-defined. - If the algorithm fails to allocate memory,
std::bad_allocis thrown.
π Notes π
For the number of elements in the range [first, last) without any additional criteria, see std::distance.
Feature-test macro
__cpp_lib_algorithm_default_value_typeβ value202403, Std(C++26), Feature: List-initialization for algorithms(1,2).
π Possible implementation π
See also the implementations of count in libstdc++ and libc++. See also the implementations of count_if in libstdc++ and libc++. Hereβs the vibe:
count
template<class InputIt, class T = typename std::iterator_traits<InputIt>::value_type>
typename std::iterator_traits<InputIt>::difference_type
count(InputIt first, InputIt last, const T& value)
{
typename std::iterator_traits<InputIt>::difference_type ret = 0;
for (; first != last; ++first)
if (*first == value)
++ret;
return ret;
}
count_if
template<class InputIt, class UnaryPred>
typename std::iterator_traits<InputIt>::difference_type
count_if(InputIt first, InputIt last, UnaryPred p)
{
typename std::iterator_traits<InputIt>::difference_type ret = 0;
for (; first != last; ++first)
if (p(*first))
++ret;
return ret;
}
πΈ Example πΈ
// Run this code
#include <algorithm>
#include <array>
#include <cassert>
#include <complex>
#include <iostream>
#include <iterator>
int main()
{
constexpr std::array v{1, 2, 3, 4, 4, 3, 7, 8, 9, 10};
std::cout << "v: ";
std::copy(v.cbegin(), v.cend(), std::ostream_iterator<int>(std::cout, " "));
std::cout << '\n';
// Determine how many integers match a target value.
for (const int target : {3, 4, 5})
{
const int num_items = std::count(v.cbegin(), v.cend(), target);
std::cout << "number: " << target << ", count: " << num_items << '\n';
}
// Use a lambda expression to count elements divisible by 4.
int count_div4 = std::count_if(v.begin(), v.end(), [](int i) { return i % 4 == 0; });
std::cout << "numbers divisible by four: " << count_div4 << '\n';
// A simplified version of `distance` with O(N) complexity:
auto distance = [](auto first, auto last)
{
return std::count_if(first, last, [](auto) { return true; });
};
static_assert(distance(v.begin(), v.end()) == 10);
std::array<std::complex<double>, 3> nums{{{4, 2}, {1, 3}, {4, 2}}};
#ifdef __cpp_lib_algorithm_default_value_type
// T gets deduced making list-initialization possible
auto c = std::count(nums.cbegin(), nums.cend(), {4, 2});
#else
auto c = std::count(nums.cbegin(), nums.cend(), std::complex<double>{4, 2});
#endif
assert(c == 2);
}
Output:
v: 1 2 3 4 4 3 7 8 9 10
number: 3, count: 2
number: 4, count: 2
number: 5, count: 0
numbers divisible by four: 3
π Defect reports π
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
- DR
LWG 283β Applied to:C++98. Behavior as published:Twas required to beEqualityComparable, but the value type ofInputItis not alwaysT. Correct behavior: removed the requirement.
β See also β
distanceβ returns the distance between two iterators (function template).ranges::countβ returns the number of elements satisfying specific criteria (C++20) (niebloid).ranges::count_ifβ returns the number of elements satisfying specific criteria (C++20) (niebloid).
Thatβs the whole page, bestie β source/version: http://cppreference.com, date: 2024.06.10, manual page: std::count,std::count_if(3). Slay, go count something. πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms