Source of search1a.cpp


  1: //search1a.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() "
 11:         "algorithm (default\nversion) to find the first occurrence of one "
 12:         "range of integer values in\na vector within another range of "
 13:         "integer values, also in a vector.";
 14:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

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

 23:     int a2[] = {3, 4, 5};
 24:     vector<int> v2(a2, a2+3);
 25:     cout << "\nHere are the contents of v2:\n";
 26:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 27:         cout << v2.at(i) << " ";
 28:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 30:     vector<int>::iterator p;

 32:     p = search(v1.begin(), v1.end(), v2.begin(), v2.end());
 33:     if (p != v1.end())
 34:         cout << "\nThe first instance of v2 in v1 begins at location "
 35:             << (int)(p-v1.begin()+1) << ".";
 36:     else
 37:         cout << "\nNo instance of v2 was found in v1.";
 38:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 40:     p = search(p+1, v1.end(), v2.begin(), v2.end());
 41:     if (p != v1.end())
 42:         cout << "\nThe next instance of v2 in v1 begins at location "
 43:             << (int)(p-v1.begin()+1) << ".";
 44:     else
 45:         cout << "\nNo further instance of v2 was found in v1.";
 46:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 48:     p = search(p+1, v1.end(), v2.begin(), v2.end());
 49:     if (p != v1.end())
 50:         cout << "\nThe next instance of v2 in v1 begins at location "
 51:             << (int)(p-v1.begin()+1) << ".";
 52:     else
 53:         cout << "\nNo further instance of v2 was found in v1.";
 54:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 55: }