transform() Function in C++

bookmark

#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
#include <iterator>
#include <iomanip>
#include <cmath>
using namespace std;
 
typedef const vector <int>& vecref;
 
int power(int a, int b)
{
    return pow(a, b);
}
 
void print(vecref a, vecref b, vecref c)
{
    cout << "b[i]   a[i]    c[i]" << endl; 
    for(int i = 0; i < a.size(); i++)
    {
        cout << setw(2) << setfill(' ') << a[i] << "   ^   "
             << setw(1) << setfill(' ') << b[i] << "   =  "
             << setw(2) << setfill(' ') << c[i] << endl;
    }
}
 
int main()
{
    vector <int> a(10), b(10), c(10);
 
    for (int i = 0; i < 10 ;i++)
    {
        a[i] = (i % 2 + 1);
        b[i] = (i % 3 + 1);
    }
    // Save the result in vector c
    cout << "Transform operation" << endl;
    transform(b.begin(), b.end(), a.begin(), c.begin(), power);
    print(b, a, c);
}

 

Output:
$ a.out
Transform operation
b[i]   a[i]    c[i]
 1   ^   1   =   1
 2   ^   2   =   4
 3   ^   1   =   3
 1   ^   2   =   1
 2   ^   1   =   2
 3   ^   2   =   9
 1   ^   1   =   1
 2   ^   2   =   4
 3   ^   1   =   3
 1   ^   2   =   1