Skip to main content

count.cpp


// Demonstration of the count algorithm
// (NDE, 2014-01-07)
#include <cstdlib>
#include <ctime>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
  // Seed pseudorandom number generator
  srand(time(NULL));
  // Populate a vector with pseudorandom integers in range 0-9
  vector<int> v;
  for (int i = 0; i < 20; ++i) {
    v.push_back(rand() % 10);
  }
  // Display vector contents
  ostream_iterator<int> out(cout, " ");
  copy(v.begin(), v.end(), out);
  cout << endl;
  // Obtain value to be counted from user
  int target;
  cout << "Enter value to be counted: ";
  cin >> target;
  // Count all occurrences of target value
  int n = count(v.begin(), v.end(), target);
  cout << n << " occurrences" << endl;
  return 0;
}