Namespaces
Variants

std:: count, std:: 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
(C++11) (C++11) (C++11)
count count_if

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
Definiert in Header <algorithm>
(1)
template < class InputIt, class T >

typename std:: iterator_traits < InputIt > :: difference_type

count ( InputIt first, InputIt last, const T & value ) ;
(constexpr seit C++20)
(bis 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 ) ;
(seit C++26)
(2)
template < class ExecutionPolicy, class ForwardIt, class T >

typename std:: iterator_traits < ForwardIt > :: difference_type
count ( ExecutionPolicy && policy,

ForwardIt first, ForwardIt last, const T & value ) ;
(seit C++17)
(bis 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 ) ;
(seit C++26)
template < class InputIt, class UnaryPred >

typename std:: iterator_traits < InputIt > :: difference_type

count_if ( InputIt first, InputIt last, UnaryPred p ) ;
(3) (constexpr seit 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) (seit C++17)

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

1) Zählt die Elemente, die gleich value sind (unter Verwendung von operator == ).
3) Zählt Elemente, für die das Prädikat p den Wert true zurückgibt.
2,4) Gleich wie (1,3) , aber ausgeführt gemäß policy .
Diese Überladungen nehmen nur dann an der Überladungsauflösung teil, wenn alle folgenden Bedingungen erfüllt sind:

std:: is_execution_policy_v < std:: decay_t < ExecutionPolicy >> ist true .

(bis C++20)

std:: is_execution_policy_v < std:: remove_cvref_t < ExecutionPolicy >> ist true .

(seit C++20)

Inhaltsverzeichnis

Parameter

first, last - das Paar von Iteratoren, das den Bereich der zu untersuchenden Elemente definiert
value - der zu suchende Wert
policy - die zu verwendende Ausführungsrichtlinie
p - unäres Prädikat, das ​ true für die erforderlichen Elemente zurückgibt.

Der Ausdruck p ( v ) muss für jedes Argument v vom Typ (möglicherweise const) VT , wobei VT der Werttyp von InputIt ist, unabhängig von der Wertkategorie , in bool konvertierbar sein und darf v nicht modifizieren. Daher ist ein Parametertyp VT & nicht zulässig , ebenso wenig wie VT , es sei denn, für VT ist eine Verschiebung äquivalent zu einer Kopie (seit C++11) . ​

Typanforderungen
-
InputIt muss die Anforderungen von LegacyInputIterator erfüllen.
-
ForwardIt muss die Anforderungen von LegacyForwardIterator erfüllen.
-
UnaryPred muss die Anforderungen von Predicate erfüllen.

Rückgabewert

Die Anzahl der Iteratoren it in dem Bereich [ first , last ) die folgende Bedingung erfüllen:

1,2) * it == value ist true .
3,4) p ( * it ) ! = false ist true .

Komplexität

Gegeben N als std:: distance ( first, last ) :

1,2) Genau N Vergleiche mit value unter Verwendung von operator == .
3,4) Genau N Anwendungen des Prädikats p .

Ausnahmen

Die Überladungen mit einem Template-Parameter namens ExecutionPolicy melden Fehler wie folgt:

  • Wenn die Ausführung einer als Teil des Algorithmus aufgerufenen Funktion eine Exception wirft und ExecutionPolicy einer der Standard-Policies ist, wird std::terminate aufgerufen. Für jede andere ExecutionPolicy ist das Verhalten implementierungsdefiniert.
  • Wenn der Algorithmus keinen Speicher allozieren kann, wird std::bad_alloc geworfen.

Hinweise

Für die Anzahl der Elemente im Bereich [ first , last ) ohne zusätzliche Kriterien, siehe std::distance .

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

Mögliche Implementierung

Siehe auch die Implementierungen von count in libstdc++ und libc++ .

Siehe auch die Implementierungen von count_if in libstdc++ und libc++ .


count (1)
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 (3)
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;
}
**Anmerkung:** Der C++-Code in den `
`-Tags wurde gemäß den Anweisungen nicht übersetzt, da er technischen Code enthält. Die HTML-Struktur und Attribute bleiben ebenfalls unverändert.

Beispiel

#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';
    // Bestimme, wie viele Ganzzahlen einem Zielwert entsprechen.
    for (const int target : {3, 4, 5})
    {
        const int num_items = std::count(v.cbegin(), v.cend(), target);
        std::cout << "Zahl: " << target << ", Anzahl: " << num_items << '\n';
    }
    // Verwende einen Lambda-Ausdruck, um durch 4 teilbare Elemente zu zählen.
    int count_div4 = std::count_if(v.begin(), v.end(), [](int i) { return i % 4 == 0; });
    std::cout << "durch vier teilbare Zahlen: " << count_div4 << '\n';
    // Eine vereinfachte Version von `distance` mit O(N)-Komplexität:
    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 wird abgeleitet, was die Listeninitialisierung ermöglicht
        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);
}

Ausgabe:

v: 1 2 3 4 4 3 7 8 9 10
Zahl: 3, Anzahl: 2
Zahl: 4, Anzahl: 2
Zahl: 5, Anzahl: 0
durch vier teilbare Zahlen: 3

Fehlerberichte

Die folgenden verhaltensändernden Fehlerberichte wurden rückwirkend auf zuvor veröffentlichte C++-Standards angewendet.

DR Angewendet auf Verhalten wie veröffentlicht Korrektes Verhalten
LWG 283 C++98 T musste EqualityComparable sein, aber
der Werttyp von InputIt ist nicht immer T
Anforderung entfernt

Siehe auch

gibt den Abstand zwischen zwei Iteratoren zurück
(Funktions-Template)
gibt die Anzahl der Elemente zurück, die bestimmte Kriterien erfüllen
(Algorithmus-Funktionsobjekt)