count_if


Count items in a range that satisfy a predicate.

Count the number of elements in the range [ first , last ) that cause pred to return true and add this count to n . Note that n is not automatically initialized to zero prior to the counting procedure.

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class InputIterator, class Predicate, class Size >
void count_if
  (
  InputIterator first,
  InputIterator last,
  Predicate pred,
  Size& n
  );
  

Complexity

Time complexity is linear, as ( last - first ) comparisons are performed. Space complexity is constant.

Example <ospace/osstd/examples/countif1.cpp>
#include <iostream>
#include <algorithm>
#include <vector>

int
odd( int a_ )
  {
  return a_ % 2;
  }

void
main()
  {
  vector< int > numbers( 100 );
  for ( int i = 0; i < 100; ++i )
      numbers[ i ] = i % 3;
  int elements = 0;

  count_if( numbers.begin(), numbers.end(), odd, elements );

  cout << "Found " << elements << " odd elements.\n";
  }

Found 33 odd elements.

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.