Source of adjacent_difference2a.cpp


  1: //adjacent_difference2a.cpp

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

  8: /**
  9: Evaluates the expression 2a+b.
 10: Pre:\n a and b contain integer values.
 11: Post:\n Returns the value 2a+b.
 12: */
 13: int f
 14: (
 15:     int a, //in
 16:     int b  //in
 17: )
 18: {
 19:     return 2*a + b;
 20: }

 22: int main()
 23: {
 24:     cout << "\nThis program illustrates the use of the STL "
 25:         "adjacent_difference() algorithm\n(extended version) from "
 26:         "<numeric> to find the value of the programmer-defined"
 27:         "\nfunction f(a,b)=2*a+b applied to successive pairs of "
 28:         "integers in one vector,\nand write these values to a second "
 29:         "vector.";
 30:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 32:     int a[] = {2, 4, 6, 8, 10};
 33:     vector<int> v1(a, a+5);
 34:     cout << "\nHere are the values in the first vector:\n";
 35:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 36:         cout << v1.at(i) << " ";
 37:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 39:     int a2[] = {1, 3, 5, 7, 9, 11, 13};
 40:     vector<int> v2(a2, a2+7);
 41:     cout << "\nAnd here are the values in the second vector:\n";
 42:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 43:         cout << v2.at(i) << " ";
 44:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 46:     cout << "\nNext a call to ajacent_difference computes the "
 47:         "function 2a+b for all integer\npairs in the first vector, "
 48:         "and writes the values to the second vector, starting\n"
 49:         "at the second position of the second vector.";
 50:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 52:     vector<int>::iterator p;
 53:     p = adjacent_difference(v1.begin(), v1.end(), v2.begin()+1, f);
 54:     cout << "\nHere are the integer values in the second vector "
 55:         "after this has been done:\n";
 56:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 57:         cout << v2.at(i) << " ";
 58:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 59:     cout << "\nAnd here is the value pointed to by the iterator "
 60:         "returned by the algorithm: ";
 61:     cout << *p;
 62:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 63: }