Skip to main content

countif.cpp


// Demonstration of the count_if algorithm
// (NDE, 2014-01-07)
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std;
bool is_negative(int value)
{
  return value < 0;
}
int main()
{
  // Seed pseudorandom number generator
  srand(time(NULL));
  // Populate a vector with pseudorandom integers in range -5 to +5
  vector<int> v;
  for (int i = 0; i < 15; ++i) {
    v.push_back(rand()%11 - 5);
  }
  // Display vector contents
  ostream_iterator<int> out(cout, " ");
  copy(v.begin(), v.end(), out);
  cout << endl;
  // Count all occurrences of negative values
  int n = count_if(v.begin(), v.end(), is_negative);
  cout << n << " negative values found" << endl;
  return 0;
}