Source of search_n1a.cpp


  1: //search_n1a.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 search_n() "
 11:         "algorithm (default\nversion) to find instances of a consecutive "
 12:         "sequence of identical values in\na vector of integers.";
 13:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

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

 22:     vector<int>::iterator p;

 24:     p = search_n(v.begin(), v.end(), 3, 9);
 25:     if (p != v.end())
 26:         cout << "\nThe first instance of three consecutive 9's begins "
 27:             "at location " << (int)(p-v.begin()+1) << ".";
 28:     else
 29:         cout << "\nNo instance of v2 was found in the vector.";
 30:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 32:     p = search_n(p+1, v.end(), 3, 9);
 33:     if (p != v.end())
 34:         cout << "\nThe next instance of three consecutive 9's begins "
 35:             "at location " << (int)(p-v.begin()+1) << ".";
 36:     else
 37:         cout << "\nNo further instance of three consecutive 9's was "
 38:             "found in the vector.";
 39:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 41:     p = search_n(p+1, v.end(), 3, 9);
 42:     if (p != v.end())
 43:         cout << "\nThe next instance of three consecutive 9's begins "
 44:             "at location " << (int)(p-v.begin()+1) << ".";
 45:     else
 46:         cout << "\nNo further instance of three consecutive 9's was "
 47:             "found in the vector.";
 48:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 50:     p = search_n(p+1, v.end(), 3, 9);
 51:     if (p != v.end())
 52:         cout << "\nThe next instance of three consecutive 9's begins "
 53:             "at location " << (int)(p-v.begin()+1) << ".";
 54:     else
 55:         cout << "\nNo further instance of three consecutive 9's was "
 56:             "found in the vector.";
 57:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 58: }