Source of nth_element1a.cpp


  1: //nth_element1a.cpp

  3: #include <iostream>
  4: #include <vector>
  5: #include <algorithm>
  6: using namespace std;

  8: int main()
  9: {
 10:     cout << "\nThis program illustrates the use of the STL "
 11:         "nth_element() algorithm (default\nversion) to partition "
 12:         "a vector of integers of size 12 around its 7th element. "
 13:         "\nThe ranges on either side of this value may or may not "
 14:         "be sorted, but the\nalgorithm does not guarantee this, "
 15:         "and you should not expect it.";
 16:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 18:     int a[] = {10,  2,  6, 11,  9,  3, 4, 12,  8,  7,  1,  5};
 19:     vector<int> v(a, a+12);
 20:     cout << "\nHere are the initial contents of the vector:\n";
 21:     for (vector<int>::size_type i=0; i<v.size(); i++)
 22:         cout << v.at(i) << " ";
 23:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 25:     cout << "\nNow we make the following call:";
 26:     cout << "\nnth_element(v.begin(), v.begin()+6, v.end());";
 27:     nth_element(v.begin(), v.begin()+6, v.end());
 28:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 30:     cout << "\nAnd here are the contents of the vector partitioned "
 31:         "around its 7th element:\n";
 32:     for (vector<int>::size_type i=0; i<v.size(); i++)
 33:         cout << v.at(i) << " ";
 34:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 35: }