Algorithm Transform Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Transform Function

Algorithm Transform Function

BLUF: Mastering Algorithm Transform Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Transform Function

C++ is renowned for its efficiency. Learn how Algorithm Transform Function enables low-level control and high-performance computing in the tutorial below.

The transform function in C++ algorithms is employed in two distinct manners:

Performing a unary operation involves applying the operator op to the elements within the range [first1, last1], and then saving the outcome in a range that commences from the designated location result.

This transform function executes a specified operation on every item within a specified range:

Performing a binary operation binary_op on the elements within the range [first1, last1] and the elements starting from the iterator first2, this function stores the outcome in a range that begins with the result iterator.

This transform function receives two pairs of ranges and executes a function with two arguments on each pair of elements from the specified ranges:

Syntax

unary operation(1)

Example

template <class InputIterator, class OutputIterator, class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);

Binary operation(2)

Example

template <class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);

Parameter

An input iterator indicating the location of the initial element within the first range to be manipulated.

An iterator indicating the position immediately after the last element of the initial range to be processed.

The iterator named first2 points to the initial element within the second range that will undergo the operation.

result: An output iterator pointing to the starting position of the range where the outcomes of the operation are stored.

A unary function is applied to every element within the range.

binary_op : A binary operation that combines two elements as its input parameters.

Return value

The transform function yields an iterator pointing to the conclusion of the modified range.

Complexity

The complexity grows linearly with the distance from the first occurrence of "first1" to the last occurrence of "last1".

Data races

The elements within the range [first1, last1) are retrieved, with each element being accessed precisely once.

The item within the range starting from the outcome is altered.

Exception safety

Raises an exception if any of the function calls, assignments, or operations on iterators trigger an exception.

Please be aware that using incorrect parameters can result in unpredictable behavior.

Example 1

Let's examine a basic example to showcase the utilization of the transform function:

Example

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <iterator>

using namespace std;

int main() {
  vector<int> v = { 3,1,4 };
  vector<string> result;

  transform(v.begin(), v.end(), back_inserter(result),
    [](int x) { return to_string(x * 2); });

  for_each(result.begin(), result.end(),
    [](const string& s) { cout << s << endl; });
}

Output:

Example 2

Let's see another simple example:

Example

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
#include <iterator>

using namespace std;

int main() {
  vector<char> v1 = { 'a','b','c' };
  vector<int> v2 = { 3,1,4 };
  vector<string> result;

  transform(v1.begin(), v1.end(), v2.begin(), back_inserter(result),
    [](char a, int b) { return string(b, a); });

  for_each(result.begin(), result.end(),
    [](const string& s) { cout << s << endl; });

return 0;
}

Output:

Output

aaa
b
cccc

Example 3

Let's see another simple example:

Example

#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);
    
    return 0;
}

Output:

Output

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

The previous instance showcases the transform procedure. The software generates a pair of vectors and modifies the third vector by adding a value equivalent to an element from the first vector raised to the power of an element in the second vector. The power function is supplied as a predicate to the transform function.

Example 4

Let's see another simple example:

Example

#include <iostream>     // cout
#include <algorithm>    // transform
#include <vector>       // vector
#include <functional>   // plus

using namespace std;

int op_increase (int i) { return ++i; }

int main () {
  vector<int> foo;
  vector<int> bar;

  // set some values:
  for (int i=1; i<6; i++)
    foo.push_back (i*10);                         // foo: 10 20 30 40 50

  bar.resize(foo.size());                         // allocate space

  transform (foo.begin(), foo.end(), bar.begin(), op_increase);
                                                  // bar: 11 21 31 41 51

  // plus adds together its two arguments:
  transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), plus<int>());
                                                  // foo: 21 41 61 81 101

  cout << "foo contains:";
  for (vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
    cout << ' ' << *it;
  cout << '\n';

  return 0;
}

Output:

Output

foo contains: 21 41 61 81 101

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience