transform知識點(diǎn)小結(jié)
一烛卧、來源與功能
來自<algorithm>頭文件佩微,對序列進(jìn)行變換操作
二缝彬、使用方式
- 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);
三、參數(shù)解釋
- first1, last1:第一個序列的元素范圍[first1,last1)
- first2:第二個序列的元素范圍[first2, first2+last1-first1)
- op:一元操作符
- binary_op:二元操作符哺眯,可以是函數(shù)指針或函數(shù)對象
四谷浅、返回值
指向結(jié)果序列最后一個元素的下一個位置
五、示例程式
#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;
}
輸出結(jié)果
51
des contains:11 21 31 41 51
source contains:21 41 61 81 101
參考鏈接
http://www.cplusplus.com/reference/algorithm/transform/?kw=transform