transform详解

1.简介

  该算法用于实行容器元素的变换操作。有如下两个使用原型,一个将迭代器区间[first,last)中元素,执行一元函数对象op操作,交换后的结果放在[result,result+(last-first))区间中。另一个将迭代器区间[first1,last1)的元素*i,依次与[first2,first2+(last-first))的元素*j,执行二元函数操作binary_op(*i,*j),交换结果放在[result,result+(last1-first1))

2.函数原型

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 );

3.参数说明

first1, last1:指出要进行元素变换的第一个迭代器区间 [first1,last1)。 
first2:指出要进行元素变换的第二个迭代器区间首个元素的迭代器位置,该区间的元素个数第一个区间相等。 
result:指出变换后的结果存放的迭代器区间的首个元素的迭代器位置
op:用一元函数对象op作为参数,执行其后返回一个结果值。它可以是一个函数或对象内的类重载operator()。 
binary_op:用二元函数对象binary_op作为参数,执行其后返回一个结果值。它可以是一个函数或对象内的类重载operator()。

4.例子

 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 }
原文地址:https://www.cnblogs.com/blueoverflow/p/4748566.html