Namespaces
Variants

std::ranges:: count, std::ranges:: count_if

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
Défini dans l'en-tête <algorithm>
Signature d'appel
(1)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class T, class Proj = std:: identity >
requires std:: indirect_binary_predicate
< ranges:: equal_to , std :: projected < I, Proj > , const T * >
constexpr std:: iter_difference_t < I >

count ( I first, S last, const T & value, Proj proj = { } ) ;
(depuis C++20)
(jusqu'à C++26)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
class T = std :: projected_value_t < I, Proj > >
requires std:: indirect_binary_predicate
< ranges:: equal_to , std :: projected < I, Proj > , const T * >
constexpr std:: iter_difference_t < I >

count ( I first, S last, const T & value, Proj proj = { } ) ;
(depuis C++26)
(2)
template < ranges:: input_range R, class T, class Proj = std:: identity >

requires std:: indirect_binary_predicate
< ranges:: equal_to ,
std :: projected < ranges:: iterator_t < R > , Proj > , const T * >
constexpr ranges:: range_difference_t < R >

count ( R && r, const T & value, Proj proj = { } ) ;
(depuis C++20)
(jusqu'à C++26)
template < ranges:: input_range R, class Proj = std:: identity ,

class T = std :: projected_value_t < ranges:: iterator_t < R > , Proj > >
requires std:: indirect_binary_predicate
< ranges:: equal_to ,
std :: projected < ranges:: iterator_t < R > , Proj > , const T * >
constexpr ranges:: range_difference_t < R >

count ( R && r, const T & value, Proj proj = { } ) ;
(depuis C++26)
template < std:: input_iterator I, std:: sentinel_for < I > S,

class Proj = std:: identity ,
std:: indirect_unary_predicate < std :: projected < I, Proj >> Pred >
constexpr std:: iter_difference_t < I >

count_if ( I first, S last, Pred pred, Proj proj = { } ) ;
(3) (depuis C++20)
template < ranges:: input_range R, class Proj = std:: identity ,

std:: indirect_unary_predicate <
std :: projected < ranges:: iterator_t < R > , Proj >> Pred >
constexpr ranges:: range_difference_t < R >

count_if ( R && r, Pred pred, Proj proj = { } ) ;
(4) (depuis C++20)

Retourne le nombre d'éléments dans la plage [ first , last ) satisfaisant des critères spécifiques.

1) Compte les éléments qui sont égaux à value .
3) Compte les éléments pour lesquels le prédicat p retourne true .
2,4) Identique à (1,3) , mais utilise r comme plage source, comme si on utilisait ranges:: begin ( r ) comme first et ranges:: end ( r ) comme last .

Les entités de type fonction décrites sur cette page sont des objets fonction d'algorithme (informellement appelés niebloids ), c'est-à-dire :

Table des matières

Paramètres

first, last - la paire itérateur-sentinelle définissant l'intervalle des éléments à examiner
r - l'intervalle des éléments à examiner
value - la valeur à rechercher
pred - prédicat à appliquer aux éléments projetés
proj - projection à appliquer aux éléments

Valeur de retour

Nombre d'éléments satisfaisant la condition.

Complexité

Exactement last - first comparaisons et projection.

Notes

Pour le nombre d'éléments dans la plage sans critères supplémentaires, voir std::ranges::distance .

Macro de test de fonctionnalité Valeur Std Fonctionnalité
__cpp_lib_algorithm_default_value_type 202403 (C++26) Initialisation par liste pour les algorithmes ( 1,2 )

Implémentation possible

**Note:** Le code C++ n'a pas été traduit conformément aux instructions, car il contient des termes spécifiques au C++ et se trouve dans des balises `
`. Seul le texte environnant aurait été traduit s'il y en avait eu.
count (1)
struct count_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity, class T = std::projected_value_t<I, Proj>>
    requires std::indirect_binary_predicate<ranges::equal_to,
                                            std::projected<I, Proj>, const T*>
    constexpr std::iter_difference_t<I>
        operator()(I first, S last, const T& value, Proj proj = {}) const
    {
        std::iter_difference_t<I> counter = 0;
        for (; first != last; ++first)
            if (std::invoke(proj, *first) == value)
                ++counter;
        return counter;
    }
    template<ranges::input_range R, class Proj = std::identity
             class T = std::projected_value_t<ranges::iterator_t<R>, Proj>>
    requires std::indirect_binary_predicate<ranges::equal_to,
                                            std::projected<ranges::iterator_t<R>, Proj>,
                                            const T*>
    constexpr ranges::range_difference_t<R>
        operator()(R&& r, const T& value, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r), value, std::ref(proj));
    }
};
inline constexpr count_fn count;
count_if (3)
struct count_if_fn
{
    template<std::input_iterator I, std::sentinel_for<I> S,
             class Proj = std::identity,
             std::indirect_unary_predicate<std::projected<I, Proj>> Pred>
    constexpr std::iter_difference_t<I>
        operator()(I first, S last, Pred pred, Proj proj = {}) const
    {
        std::iter_difference_t<I> counter = 0;
        for (; first != last; ++first)
            if (std::invoke(pred, std::invoke(proj, *first)))
                ++counter;
        return counter;
    }
    template<ranges::input_range R, class Proj = std::identity,
             std::indirect_unary_predicate<
                 std::projected<ranges::iterator_t<R>, Proj>> Pred>
    constexpr ranges::range_difference_t<R>
        operator()(R&& r, Pred pred, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r),
                       std::ref(pred), std::ref(proj));
    }
};
inline constexpr count_if_fn count_if;

Exemple

#include <algorithm>
#include <cassert>
#include <complex>
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v{1, 2, 3, 4, 4, 3, 7, 8, 9, 10};
    namespace ranges = std::ranges;
    // déterminer combien d'entiers dans un std::vector correspondent à une valeur cible
    int target1 = 3;
    int target2 = 5;
    int num_items1 = ranges::count(v.begin(), v.end(), target1);
    int num_items2 = ranges::count(v, target2);
    std::cout << "nombre : " << target1 << " compte : " << num_items1 << '\n';
    std::cout << "nombre : " << target2 << " compte : " << num_items2 << '\n';
    // utiliser une expression lambda pour compter les éléments divisibles par 3
    int num_items3 = ranges::count_if(v.begin(), v.end(), [](int i){ return i % 3 == 0; });
    std::cout << "nombre divisible par trois : " << num_items3 << '\n';
    // utiliser une expression lambda pour compter les éléments divisibles par 11
    int num_items11 = ranges::count_if(v, [](int i){ return i % 11 == 0; });
    std::cout << "nombre divisible par onze : " << num_items11 << '\n';
    std::vector<std::complex<double>> nums{{4, 2}, {1, 3}, {4, 2}};
    #ifdef __cpp_lib_algorithm_default_value_type
        auto c = ranges::count(nums, {4, 2});
    #else
        auto c = ranges::count(nums, std::complex<double>{4, 2});
    #endif
    assert(c == 2);
}

Sortie :

nombre : 3 compte : 2
nombre : 5 compte : 0
nombre divisible par trois : 3
nombre divisible par onze : 0

Voir aussi

retourne la distance entre un itérateur et un sentinelle, ou entre le début et la fin d'une plage
(objet fonction algorithme)
crée une sous-plage à partir d'un itérateur et d'un compteur
(objet point de personnalisation)
une view qui consiste en les éléments d'une range qui satisfont un prédicat
(modèle de classe) (objet adaptateur de plage)
retourne le nombre d'éléments satisfaisant des critères spécifiques
(modèle de fonction)