Monday, September 2, 2019

Simple example of transform from C++ algorithm library

Overview

This article shows simple example of the transform function from algorithm library of C++ and its syntax.




Example

The following code is one of the simple example codes of transform.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

int add_three(int v){
    return v + 3;
}

int main(){
    vector<int> a {1,2,3};

    vector<int> b;
    b.resize(a.size());

    transform(a.begin(), a.end(), b.begin(), add_three);

    for (auto &v : b){cout << v << endl;}
    return 0;
}

4
5
6

To the a, add_three function is executed by transform function and the output is held by the b. Bit more concretely, on this code, the function which is to add 3 to the input and return it is executed to a and the output is kept in b.

Syntax

We can use transform with unary operation and binary operation.
I'll touch only unary operation usage.
On this case, transform accepts initial and final position’s iterator. To that range, the given function is executed. We need to give the initial position’s iterator of another range to hold the output.

transform(input_initial_iterator, input_final_iterator, output_initial_iterator, function)