Pages

Thursday, March 18, 2010

STL. Transform

Here is a simple program using transform algorithm:
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;

int sum(int n, int m) { return (n + m); }

int main (int argc, char * const argv[]) {

int i1[] = { 0, 1, 2, 3, 4, 5 };
int i2[] = { 6, 7, 8, 9, 0, 1 };

ostream_iterator<int> out(cout, " ");
transform(&i1[0], &i1[6], &i2[0], out, sum);
return 0;
}
Here is the output in the console:

Program loaded.
run
[Switching to process 295]
Running…
6 8 10 12 4 6 
Debugger stopped.
Program exited with status value:0.

A bit more interesting program:
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
using namespace std;

string makeFullName(string& str1, string& str2)
{
return str1 + " " + str2;
}

int main (int argc, char * const argv[]) {
vector<string> first;
vector<string> second;

first.push_back("George");
first.push_back("Pavel");
first.push_back("Ivan");

second.push_back("Reznik");
second.push_back("Bush");
second.push_back("Ivanov");

ostream_iterator<string> out(cout, ", ");
transform(first.begin(), first.end(), second.begin(), out, makeFullName);


return 0;
}
The output:

Program loaded.
run
[Switching to process 395]
Running…
George Reznik, Pavel Bush, Ivan Ivanov, 
Debugger stopped.
Program exited with status value:0.

No comments:

Post a Comment