@specsoftdev live:.cid.8e17e9b93cabb607 specsoftdev@gmail.com
std::ranges::count_if
Актуально для C++23.

#include <algorithm>
Актуально на 2025-05-13.


Define overload #1
template<input_iterator I, sentinel_for<I> S, class Proj = identity, indirect_unary_predicate<projected<I, Proj>> Pred>
constexpr iter_difference_t<I>
ranges::count_if(I first, S last, Pred pred, Proj proj = {});

Подсчитывает количество элементов в диапазоне [first, last] для которых пользовательский предикат вернёт true.
Вернёт их количество.
Example, possible implementation
Define overload #2
template<input_range R, class Proj = identity, indirect_unary_predicate<projected<iterator_t<R>, Proj>> Pred>
constexpr range_difference_t<R>
ranges::count_if(R&& r, Pred pred, Proj proj = {});

Подсчитывает количество элементов в диапазоне "r" для которых пользовательский предикат вернёт true.
Вернёт их количество.
Example, possible implementation

Сложность

Линейная - O(n).



Examples


Example 1:
#include <iostream>
#include <algorithm>

namespace range = std::ranges;

int main()
{
    auto list = {1, 2, 3, 1, 2, 3, 3};
    auto count3 = range::count_if(list, [](auto s){return s == 3;});
    auto count7 = range::count_if(list, [](auto s){return s == 7;});
    std::cout << "count3: " << count3 << std::endl;
    std::cout << "count7: " << count7 << std::endl;
    return 0;
}


count3: 3
count7: 0





Changelog

C++20
Введён в стандарт.


See also

TODO

This page was last modified on 2025-05-13