Source of vector_d.cpp


  1: //vector_d.cpp

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

  9: int main()
 10: {
 11:     cout << "\nThis program illustrates the use of several "
 12:             "STL algorithms with vector objects."
 13:             "\nFrom <algorithm> we show max, min, max_element, "
 14:             "min_element, count, and sort."
 15:             "\nFrom <numeric> we show accumulate.";
 16:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 18:     int a[] = {1, 8, 2, 8, 12, 3, -1, 8, 4, 8, 5};
 19:     vector<int> v(a, a+sizeof(a)/sizeof(int));

 21:     cout << "\nHere are the values in the vector v:\n";
 22:     copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
 23:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 25:     cout << "\nNow we compare the first and last values.";
 26:     cout << "\nMaximum of first and last values = "
 27:          << max(v.front(), v.back());
 28:     cout << "\nMinimum of first and last values = "
 29:          << min(v.front(), v.back()) << endl;
 30:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 32:     cout << "\nHere are the maximum and minimum values.";
 33:     cout << "\nMaximum value in the vector = "
 34:          << *max_element(v.begin(), v.end());
 35:     cout << "\nMinimum value in the vector = "
 36:          << *min_element(v.begin(), v.end());
 37:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 39:     cout << "\nHere is the number of times the value 8 appears: ";
 40:     cout << (int)count(v.begin(), v.end(), 8) << endl;
 41:     //Note that algorithm count returns a value of type size_t.
 42:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');

 44:     cout << "\nHere are the values sorted in ascending order:\n";
 45:     sort(v.begin(), v.end());
 46:     copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
 47:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 49:     cout << "\nFinally, here is the sum of all the values: ";
 50:     cout << accumulate(v.begin(), v.end(), 0) << endl;
 51:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 52: }