C++/STL Algorithms Non modifying sequence operations/count if

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Use std::count_if to count number of elements in vector that are greater than 9

<source lang="cpp">


  1. include <iostream>

using std::cout; using std::endl;

  1. include <algorithm>
  2. include <numeric>
  3. include <vector>
  4. 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

*/        
 </source>