Noeud:transform, Noeud « Next »:partition, Noeud « Previous »:find, Noeud « Up »:Generic Algorithms and Function Objects
transform
isn't too disimilar to for_each
, in the sense
that both let us modify some range of elements. However, whereas with
for_each
we are modifying the range we pass in, with
transform
we can make changes to another range of elements. The
signature for passing in a unary operation is as follows:
OutputIterator transform(InputIterator begin, InputIterator end, OutputIterator result, UnaryOp op);...which applies
op
for each element in the range begin
to
end
, writing the result of each application of op
to
result
. There is also a version of transform
that takes a
binary operation:
OutputIterator transform(InputIterator1 begin1, InputIterator1 end1, InputIterator2 begin2, OutputIterator result, BinaryOp op);...which, for all elements in the range
begin1
to end1
,
applies op
on each element in the range with, starting with
begin1
and begin2
, up to end1
.
Here's a simple example:
/* generic4.cc * Compiled using g++ generic4.cc -o generic4 * Run using ./generic4 */ #include <algorithm> #include <functional> #include <vector> int main() { std::vector<int> v1, v2(10, 0); for (int i=0; i<10; i++) v1.push_back(i*10); transform(v1.begin(), v1.end(), v2.begin(), bind2nd(divides<int>(), 10)); std::vector<int>::iterator pos; for (pos = v2.begin(); pos != v2.end(); ++pos) cout << *pos << " "; return 0; }
Example 3.22: generic4.cc
We declare two vectors, populating v2
with 10 elements each with a
value of 0. The first vector is initialised with the values 0 through 90,
incrementing by ten for each element. We use the bind2nd
function
adaptor to divide each value of v1
that we encounter by 10, and the
result is copied into v2
. The end result is that v2
contains
copies of all the values held in v1
, divided by 10:
0 1 2 3 4 5 6 7 8 9