Namensräume
Varianten
Aktionen

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

Von cppreference.com
< cpp‎ | algorithm‎ | ranges
 
 
Algorithmenbibliothek
Beschränkte Algorithmen und Algorithmen für Bereiche (C++20)
Beschränkte Algorithmen, z.B. ranges::copy, ranges::sort, ...
Ausführungsrichtlinien (C++17)
Nicht-modifizierende Sequenzoperationen
Stapeloperationen
(C++17)
Suchoperationen
(C++11)                (C++11)(C++11)

Modifizierende Sequenzoperationen
Kopieroperationen
(C++11)
(C++11)
Tauschoperationen
Transformationsoperationen
Generierungsoperationen
Entfernungsoperationen
Ordnungsändernde Operationen
(bis C++17)(C++11)
(C++20)(C++20)
Stichprobenoperationen
(C++17)

Sortier- und verwandte Operationen
Partitionierungsoperationen
Sortieroperationen
Binäre Suchoperationen
(auf partitionierten Bereichen)
Mengenoperationen (auf sortierten Bereichen)
Zusammenführungsoperationen (auf sortierten Bereichen)
Heapoperationen
Minimum/Maximum-Operationen
(C++11)
(C++17)
Lexikographische Vergleichsoperationen
Permutationsoperationen
C-Bibliothek
Numerische Operationen
Operationen auf uninitialisiertem Speicher
 
Eingeschränkte Algorithmen
Alle Namen in diesem Menü gehören zum Namespace std::ranges
Nicht-modifizierende Sequenzoperationen
Modifizierende Sequenzoperationen
Partitionierungsoperationen
Sortieroperationen
Binäre Suchoperationen (auf sortierten Bereichen)
       
       
Mengenoperationen (auf sortierten Bereichen)
Heapoperationen
Minimum/Maximum-Operationen
       
       
Permutationsoperationen
Faltoperationen
Operationen auf uninitialisiertem Speicher
Rückgabetypen
 
Definiert in Header <algorithm>
Aufruf-Signatur
(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 = {} );
(seit C++20)
(bis 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 = {} );
(seit 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 = {} );
(seit C++20)
(bis 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 = {} );
(seit 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) (seit 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) (seit C++20)

Gibt die Anzahl der Elemente im Bereich [firstlast) zurück, die bestimmte Kriterien erfüllen.

1) Zählt die Elemente, die gleich value sind.
3) Zählt Elemente, für die der Prädikator p true zurückgibt.
2,4) Entspricht (1,3), verwendet aber r als Quellbereich, so als ob ranges::begin(r) als first und ranges::end(r) als last verwendet würden.

Die auf dieser Seite beschriebenen funktionsähnlichen Entitäten sind Algorithmus-Funktionsobjekte (informell als niebloids bekannt), d.h.

Inhalt

[edit] Parameter

first, last - das Iterator-Sentinel-Paar, das den Bereich der zu untersuchenden Elemente definiert
r - der zu untersuchende Elementbereich
value - Der zu suchende Wert
pred - Prädikat, das auf die projizierten Elemente angewendet wird
proj - Projektion, die auf die Elemente angewendet wird

[edit] Rückgabewert

Anzahl der Elemente, die die Bedingung erfüllen.

[edit] Komplexität

Genau last - first Vergleiche und Projektionen.

[edit] Hinweise

Für die Anzahl der Elemente im Bereich ohne zusätzliche Kriterien siehe std::ranges::distance.

Feature-Test-Makro Wert Std Feature
__cpp_lib_algorithm_default_value_type 202403 (C++26) Listeninitialisierung für Algorithmen (1,2)

[edit] Mögliche Implementierung

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;

[edit] Beispiel

#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;
 
    // determine how many integers in a std::vector match a target value.
    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 << "number: " << target1 << " count: " << num_items1 << '\n';
    std::cout << "number: " << target2 << " count: " << num_items2 << '\n';
 
    // use a lambda expression to count elements divisible by 3.
    int num_items3 = ranges::count_if(v.begin(), v.end(), [](int i){ return i % 3 == 0; });
    std::cout << "number divisible by three: " << num_items3 << '\n';
 
    // use a lambda expression to count elements divisible by 11.
    int num_items11 = ranges::count_if(v, [](int i){ return i % 11 == 0; });
    std::cout << "number divisible by eleven: " << 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);
}

Ausgabe

number: 3 count: 2
number: 5 count: 0
number divisible by three: 3
number divisible by eleven: 0

[edit] Siehe auch

gibt die Distanz zwischen einem Iterator und einem Sentinel zurück oder die Distanz zwischen dem Anfang und dem Ende eines Bereichs
(Algorithmus-Funktionsobjekt)[bearbeiten]
erstellt einen Subrange aus einem Iterator und einer Anzahl
(Customization Point Objekt)[edit]
ein view, der aus den Elementen eines range besteht, die ein Prädikat erfüllen
(Klassen-Template) (Range-Adaptor-Objekt)[edit]
Gibt die Anzahl der Elemente zurück, die bestimmte Kriterien erfüllen
(Funktionstempelat) [edit]