Use the count_if algorithm with the unary predicate IsEven : Algorithm « vector « C++ Tutorial






#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
template <typename elementType>
bool IsEven (const elementType& number)
{
    return ((number % 2) == 0);
}

int main ()
{
    vector <int> v;

    for (int nNum = -9; nNum < 10; ++ nNum)
        v.push_back (nNum);

    vector <int>::const_iterator i;
    for ( i = v.begin (); i != v.end (); ++ i )
        cout << *i << ' ';

    cout << v.size () << "' elements" << endl;

    // Use the count_if algorithm with the unary predicate IsEven:
    size_t nNumEvenElements = count_if (v.begin (),v.end (), IsEven <int> );

    cout << "Number of even elements: " << nNumEvenElements << endl;
    cout << "Number of odd elements: ";
    cout << v.size () - nNumEvenElements << endl;

    return 0;
}








16.32.Algorithm
16.32.1.Using the for_each() Algorithm
16.32.2.find_if, bind2nd and greater_equal
16.32.3.Mutating Sequence Algorithm
16.32.4.Use the count_if algorithm with the unary predicate IsEven
16.32.5.Use count to determine the number of '0's in the vector
16.32.6.merge the elements of NumbersVestor and NumbersList and place the results in NumbersDeque
16.32.7.shuffle the elements in a random order
16.32.8.Fill elements in a vector with custom generator
16.32.9.random number generation in quantitative finance
16.32.10.Inner product of a vector and another vector
16.32.11.The adjacent difference of the vector
16.32.12.for_each element in a vector apply custom function
16.32.13.Find the first element in the range (first, last + 1) that matches value