Use std::count_if to count number of elements in vector that are greater than 9 : count_if « STL Algorithms Non modifying sequence operations « C++ Tutorial






#include <iostream>
using std::cout;
using std::endl;

#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>

bool greater9( int );

int main()
{
   std::ostream_iterator< int > output( cout, " " );

   int a2[ 10 ] = { 100, 2, 8, 1, 50, 3, 8, 8, 9, 10 };
   std::vector< int > v2( a2, a2 + 10 ); // copy of a2
   cout << "\n\nVector v2 contains: ";
   std::copy( v2.begin(), v2.end(), output );

   // count number of elements in v2 that are greater than 9
   int result = std::count_if( v2.begin(), v2.end(), greater9 );
   cout << "\nNumber of elements greater than 9: " << result;

   cout << endl;
   return 0;
}
bool greater9( int value )
{
   return value > 9;
}
Vector v2 contains: 100 2 8 1 50 3 8 8 9 10
Number of elements greater than 9: 3








25.5.count_if
25.5.1.Use std::count_if to count number of elements in vector that are greater than 9
25.5.2.count_if(): A unary predicate that determines if number is divisible by 3