transform |
Transform one sequence into another.
The first version traverses the sequence [ first ... last ) and stores the results of invoking op on each element into a sequence of the same size starting at result . The second version uses a pair of iterators i and j to traverse two sequences, starting at first1 and first2 , respectively, until i reaches last1 . The second version stores the results of invoking binary_op on the elements referenced by the iterator pair into a sequence of the same size starting at result . Both versions return an iterator positioned immediately after the last new element.
#include <algorithm>
template
<
class InputIterator,
class OutputIterator,
class UnaryOperation
>
OutputIterator transform
(
InputIterator first,
InputIterator last,
OutputIterator result,
UnaryOperation op
);
template
<
class InputIterator1,
class InputIterator2,
class OutputIterator,
class BinaryOperation
>
OutputIterator transform
(
InputIterator1 first1,
InputIterator1 last1,
InputIterator2 first2,
OutputIterator result,
BinaryOperation binary_op
);
Time complexity is linear, as (
last1 - first1 )
operations are performed. Space complexity is constant.
#include <iostream>
#include <algorithm>
int numbers[ 6 ] = { -5, -1, 0, 1, 6, 11 };
int
negate_int( int a_ )
{
return -a_;
}
void
main()
{
int result[ 6 ];
transform
(
numbers,
numbers + 6,
result,
negate_int
);
for ( int i = 0; i < 6; ++i )
cout << result[ i ] << ` `;
cout << "\n";
}
5 1 0 -1 -6 -11
#include <iostream>
#include <string.h>
#include <algorithm>
#include <iterator>
int trans[] = {-4, 4, -6, -6, -10, 0, 10, -6, 6, 0, -1, -77};
char n[] = "Larry Mullen";
char
map_char( char a_, int b_ )
{
return char( a_ + b_ );
}
void
main()
{
const unsigned count = ::strlen( n );
ostream_iterator< char > iter( cout );
transform( n, n + count, trans, iter, map_char );
cout << "\n";
}
Hello World!
Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.