Translations of this page?:

transform

Syntax:

    #include <algorithm>
    output_iterator transform( input_iterator start, input_iterator end, output_iterator result, UnaryFunction f );
    output_iterator transform( input_iterator start1, input_iterator end1, input_iterator2 start2, output_iterator result, BinaryFunction f );

The transform algorithm applies the function f to some range of elements, storing the result of each application of the function in result.

The first version of the function applies f to each element in [start,end) and assigns the first output of the function to result, the second output to (result+1), etc.

The second version of the transform works in a similar manner, except that it is given two ranges of elements and calls a binary function on a pair of elements.

For example, the following code uses transform to convert a string to uppercase using the toupper function:

    string s("hello");
    transform(s.begin(), s.end(), s.begin(), toupper);
// in some compilers, you have to add a cast to "toupper" to resolve ambiguity:
//  transform(s.begin(), s.end(), s.begin(), (int (*)(int))toupper);
    cout << s << endl;

The above code displays the following output:

    HELLO

Alternatively, the following example shows how user-defined functions can be used to transform a vector:

int increment(int i) { return ++i; }
int sum(int a, int b) { return a+b; }
 
int main() {
  vector<int> v1;
  for(int i=1; i<6; i++) v1.push_back (i*i);                    // v1: 1 4 9  16 25
 
  vector<int> v2(v1.size());
  transform(v1.begin(), v1.end(), v2.begin(), increment);       // v2: 2 5 10 17 26
 
  // add the elements of v1 and v2 together, store the result in v1
  transform(v1.begin(), v1.end(), v2.begin(), v1.begin(), sum); // v1: 3 9 19 33 51
 
  return 0;
}

Related Topics: copy, fill, generate

 
• • • IndexRecent changesRSScc