C++ examples for STL Algorithm:transform
Demonstrate the two-sequence form of transform()
#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()/*from w w w . j a v a2 s . co m*/ { int i; // Now, demonstrate the two-sequence form of transform() cout << "Demonstrate double-sequence form of transform().\n"; vector<int> v3, v4, v5(10); for(i = 0; i < 10; ++i) v3.push_back(i); for(i = 10; i < 20; ++i) { if(i%2) v4.push_back(i); else v4.push_back(-i); } show("Contents of v3:\n", v3); show("Contents of v4:\n", v4); cout << endl; cout << "Compute midpoints between v3 and v4 and store results in v5.\n"; transform(v3.begin(), v3.end(), v4.begin(), v5.begin(), midpoint); show("Contents of v5:\n", v5); return 0; } 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 }