該算法用於實行容器元素的變換操作。有如下兩個使用原型,一個將迭代器區間[first,last)中元素,執行一元函數對象op操作,交換後的結果放在[result,result+(last-first))區間中。另一個將迭代器區間[first1,last1)的元素*i,依次與[first2,first2+(last-first))的元素*j,執行二元函數操作binary_op(*i,*j),交換結果放在[result,result+(last1-first1))。
1 template < class InputIterator, class OutputIterator, class UnaryOperator > 2 OutputIterator transform ( InputIterator first1, InputIterator last1, 3 OutputIterator result, UnaryOperator op ); 4 5 template < class InputIterator1, class InputIterator2, 6 class OutputIterator, class BinaryOperator > 7 OutputIterator transform ( InputIterator1 first1, InputIterator1 last1, 8 InputIterator2 first2, OutputIterator result, 9 BinaryOperator binary_op );
first1, last1:指出要進行元素變換的第一個迭代器區間 [first1,last1)。
first2:指出要進行元素變換的第二個迭代器區間的首個元素的迭代器位置,該區間的元素個數和第一個區間相等。
result:指出變換後的結果存放的迭代器區間的首個元素的迭代器位置。
op:用一元函數對象op作為參數,執行其後返回一個結果值。它可以是一個函數或對象內的類重載operator()。
binary_op:用二元函數對象binary_op作為參數,執行其後返回一個結果值。它可以是一個函數或對象內的類重載operator()。
1 #include <iostream>
2 #include <algorithm>
3 #include <vector>
4 using namespace std;
5
6 int op_increase (int i) { return ++i; }
7 int op_sum (int i, int j) { return i+j; }
8
9 int main () {
10 vector<int> first;
11 vector<int> second;
12 vector<int>::iterator it;
13
14 // set some values:
15 for (int i=1; i<6; i++) first.push_back (i*10); // first: 10 20 30 40 50
16
17 second.resize(first.size()); // allocate space
18 transform (first.begin(), first.end(), second.begin(), op_increase);
19 // second: 11 21 31 41 51
20
21 transform (first.begin(), first.end(), second.begin(), first.begin(), op_sum);
22 // first: 21 41 61 81 101
23
24 cout << "first contains:";
25 for (it=first.begin(); it!=first.end(); ++it)
26 cout << " " << *it;
27
28 cout << endl;
29 return 0;
30 }