In this section, we are going to use std::transform in order to modify the items of a vector while copying them:
- As always, we first need to include all the necessary headers and to spare us some typing, we declare that we use the std namespace:
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
using namespace std;
- A vector with some simple integers will do the job as an example source data structure:
int main()
{
vector<int> v {1, 2, 3, 4, 5};
- Now, we copy all the items to an ostream_iterator adapter in order to print them. The transform function accepts a function object, which accepts items of the container payload type and transforms them during each copy operation. In this case, we calculate the square of each number item, so the code will print the squares of the items in the vector without us having to store them anywhere:
transform(begin(v), end(v),
ostream_iterator<int>{cout, ", "},
[] (int i) { return i * i; });
cout << 'n';
- Let's do another transformation. From the number 3, for example, we could generate a nicely readable string such as 3^2 = 9. The following int_to_string function object does just that using the std::stringstream object:
auto int_to_string ([](int i) {
stringstream ss;
ss << i << "^2 = " << i * i;
return ss.str();
});- The function we just implemented returns us string values from integer values. We could also say it maps from integers to strings. Using the transform function, we can copy all such mappings from the integer vector into a string vector:
vector<string> vs;
transform(begin(v), end(v), back_inserter(vs),
int_to_string);
- After printing those, we're done:
copy(begin(vs), end(vs),
ostream_iterator<string>{cout, "n"});
}
- Let's compile and run the program:
$ ./transforming_items_in_containers
1, 4, 9, 16, 25,
1^2 = 1
2^2 = 4
3^2 = 9
4^2 = 16
5^2 = 25