Demonstrate the single-sequence form of transform(). - C++ STL Algorithm

C++ examples for STL Algorithm:transform

Description

Demonstrate the single-sequence form of transform().

Demo Code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double reciprocal(double val);
int midpoint(int a, int b);
template<class T> void show(const char *msg, vector<T> vect);
int main()//  w  w  w .  ja va 2 s  .  c  om
{
  int i;
  // First, demonstrate the single-sequence form of transform().
  vector<double> v;
  // Put values into v.
  for (i = 1; i < 10; ++i)
    v.push_back((double)i);
  cout << "Demonstrate single-sequence form of transform().\n";
  show("Initial contents of v:\n", v);
  cout << endl;
  // Transform v by applying the reciprocal() function.
  // Put the result back into v.
  cout << "Compute reciprocals for v and store the results back in v.\n";
  transform(v.begin(), v.end(), v.begin(), reciprocal);
  show("Transformed contents of v:\n", v);
  // Transform v a second time, putting the result into a new sequence.
  cout << "Transform v again. This time, store the results in v2.\n";
  vector<double> v2(10);
  transform(v.begin(), v.end(), v2.begin(), reciprocal);
  show("Here is v2:\n", v2);
  cout << endl;
}
template<class T> void show(const char *msg, vector<T> vect) {
  cout << msg;
  for (unsigned i = 0; i < vect.size(); ++i)
    cout << vect[i] << " ";
  cout << "\n";
}
// Return the whole-number midpoint between two values.
int midpoint(int a, int b) {
  return((a - b) / 2) + b;
}
// Return the reciprocal of a double.
double reciprocal(double val) {
  if (val == 0.0) return 0.0;
  return 1.0 / val; // return reciprocal
}

Result


Related Tutorials