Skip to main content

replace.cpp


/*
   Demonstration of the replace algorithm.
   This program also shows how an ostream_iterator can be used with
   the copy algorithm to copy the contents of a vector to cout.
   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 target value and its replacement
  int target, replacement;
  cout << "Enter value to be replaced: ";
  cin >> target;
  cout << "Enter value that will replace it: ";
  cin >> replacement;
  // Replace all occurrences of target value
  replace(v.begin(), v.end(), target, replacement);
  // Display vector contents again
  copy(v.begin(), v.end(), out);
  cout << endl;
  return 0;
}