算法transform()提供两种能力
1.第一形式有4个参数。把源区间的元素转换到目标区间(转换的意思包含了复制和修改)
2.第二形式有5个参数,将前两个源序列中的元素合并,并将结果写入目标区间
转换元素
OutputIterator transform(InputIterator sourceBeg,InputIterator sourceEnd,
OutputIterator destBeg,UnaryFunc op)
- 针对源区间[sourceBeg,sourceEnd)中的每一个元素调用:op(elem),并将结果写到以destBeg起始的目标区间内
- 返回目标区间内“最后一个被转换元素”的下一位置,也就是第一个未被覆盖的元素的位置
- 调用者必须确保目标区间有足够空间,否则就必须使用插入型迭代器
- sourceBeg与destBeg可以相同,所以可以使用这个算法来变动某一序列内的元素
#include "algostuff.h"
using namespace std;
int main()
{
vector<int> col1;
list<int> col2;
INSERT_ELEMENTS(col1, 1, 9);
PRINT_ELEMENTS(col1, "col1: ");
//negate all elements in col1
transform(col1.begin(), col1.end(), col1.begin(), negate<int>());
PRINT_ELEMENTS(col1, "negate col1: ");
//transform elements of col1 into col2 with 10 times their value
transform(col1.begin(), col1.end(), back_inserter(col2), bind2nd(multiplies<int>(), 10));
PRINT_ELEMENTS(col2, "col2: ");
//print col2 negatively and in reverse order
transform(col2.rbegin(), col2.rend(), ostream_iterator<int>(cout, " "), negate<int>());
return 0;
}
运行结果如下
将两序列的元素加以结合
OutputIteratot transform(InputIterator1 source1Beg,InputIterator source1End
InputIterator2 source2Beg,
OutputIterator destBeg,
BinaryFunc op)
- 针对第一个源区间[source1Beg,source1End)以及“从source2Beg开始的第二个源区间”的对应元素,调用op(source1Elem,source2Elem),并将结果写入以destBeg起始的目标区间
- 返回目标区间内的“最后一个 被转换元素”的下一个位置,就是第一个未被覆盖的元素的位置
- 调用者必须保证第二源区间有足够空间(至少有和第一源区间相同的空间大小)
- 必须保证目标区间有足够空间,否则需要使用插入型迭代器
- source1Beg,source2Beg,destBeg可以相同,所以可以让元素自己和自己结合再将结果放在某个区间
#include "algostuff.h"
using namespace std;
int main()
{
vector<int> col1;
list<int> col2;
INSERT_ELEMENTS(col1, 1, 9);
PRINT_ELEMENTS(col1, "col1: ");
//square each element
transform(col1.begin(), col1.end(), col1.begin(), col1.begin(), multiplies<int>());
PRINT_ELEMENTS(col1, "square col1: ");
//add each element traversed forward with each element traversed backward
//and insert into col2
transform(col1.begin(), col1.end(), col1.rbegin(), back_inserter(col2), plus<int>());
PRINT_ELEMENTS(col2, "col2: ");
//difference of col1 and col2
cout << "diff: ";
transform(col1.begin(), col1.end(), col2.begin(), ostream_iterator<int>(cout, " "),minus<int>());
}
运算结果如下
其中包含的头文件 algostuff.h为 (包含了几个常用的操作,避免重复编写的麻烦)
#ifndef ALGOSTUFF_HPP
#define ALGOSTUFF_HPP
#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <functional>
#include <numeric>
using namespace std;
template <class T>
inline void PRINT_ELEMENTS(const T& coll, const char* optcstr = "")
{
typename T::const_iterator pos;
std::cout << optcstr;
for (pos = coll.begin(); pos != coll.end(); ++pos)
{
cout << *pos << " ";
}
cout << endl;
}
template<class T>
inline void INSERT_ELEMENTS(T& coll, int first, int last)
{
for (int i = first; i <= last; ++i)
{
coll.insert(coll.end(), i);
}
}
#endif