transform知识点小结
一、来源与功能
来自<algorithm>头文件,对序列进行变换操作
二、使用方式
- unary operation(1)
template <class InputIterator, class OutputIterator, class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);
- binary operation(2)
template <class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
三、参数解释
- first1, last1:第一个序列的元素范围[first1,last1)
- first2:第二个序列的元素范围[first2, first2+last1-first1)
- op:一元操作符
- binary_op:二元操作符,可以是函数指针或函数对象
四、返回值
指向结果序列最后一个元素的下一个位置
五、示例程式
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
namespace sxg00 {
void printSeq(vector<int>& vec) {
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
cout << '\n';
}
int op_increase(int i) {
return ++i;
}
void test_transform() {
vector<int> source;
for (int i=1; i<6; i++)
source.push_back (i*10);
vector<int> des;
des.resize(source.size());
// test transform Unary operation
/**
unary operation(1)
template <class InputIterator, class OutputIterator, class UnaryOperation>
OutputIterator transform (InputIterator first1, InputIterator last1,
OutputIterator result, UnaryOperation op);
*/
vector<int>::iterator it = transform(source.begin(), source.end(), des.begin(), op_increase);
cout << *(--it) << endl;
cout << "des contains:";
printSeq(des);
// test transform Binary operation
/**
binary operation(2)
template <class InputIterator1, class InputIterator2,
class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, OutputIterator result,
BinaryOperation binary_op);
*/
transform(source.begin(), source.end(), des.begin(), source.begin(), std::plus<int>());
cout << "source contains:";
printSeq(source);
}
}
int main() {
sxg00::test_transform();
return 0;
}
输出结果
51
des contains:11 21 31 41 51
source contains:21 41 61 81 101
参考链接
http://www.cplusplus.com/reference/algorithm/transform/?kw=transform