Skip to main content

sortdemo.cpp


/*
   Demonstration of the sort 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-99
  vector<int> v;
  for (int i = 0; i < 10; ++i) {
    v.push_back(rand() % 100);
  }
  // Display vector contents
  ostream_iterator<int> out(cout, " ");
  cout << "Original: ";
  copy(v.begin(), v.end(), out);
  cout << endl;
  // sort vector
  sort(v.begin(), v.end());
  // Display vector contents again
  cout << "Ascending: ";
  copy(v.begin(), v.end(), out);
  cout << endl;
  // Sort into descending order
  sort(v.begin(), v.end(), greater<int>());
  // Display vector contents one final time
  cout << "Descending: ";
  copy(v.begin(), v.end(), out);
  cout << endl;
  return 0;
}