transform:
STL中用於將容器中元素的變換操作
模板函數,函數原型爲:
//將 [first1,last1) 區間中的元素通過
UnaryOperatorop
操作,UnaryOperatorop
的返回保存在 result 中
template<class InputIterator,class OutputIterator,class UnaryOperator>
OutputIterator transform(InputIterator first1,InputIterator last1,OutputIterator result,UnaryOperatorop);
//將 [first1,last1) 區間中的元素, [first2,first2+(last1-first)) 區間中的元素 通過二元運算傳遞到 result 中
template<class InputIterator1,class InputIterator2,class OutputIterator,class BinaryOperator>
OutputIterator transform(InputIterator1 first1,InputIterator1 last1,InputIterator2 first2,OutputIterator result,BinaryOperator binary_op);
例子程序
:/*************************************************************************
> File Name: test.cpp
> Author: Antlook
> Mail: [email protected]
> Created Time: 2016年01月24日 星期日 21時03分27秒
************************************************************************/
#include<iostream>
#include<algorithm>
#include<string>
#include<cctype>
#include<vector>
using namespace std;
int getsum(int x, int y){
return x+y;
}
int main()
{
string str = "hello world!";
transform(str.begin(),str.end(),str.begin(),::toupper);
cout<<str<<endl;
vector<int> vec1;
for(int i = 1; i < 10; i++)
vec1.push_back(i);
vector<int>vec2{vec1};
transform(vec1.begin(), vec1.end(), vec2.begin(), vec2.begin(),::getsum);
for(vector<int>::iterator it = vec2.begin(); it != vec2.end(); it++){
cout<<*it<<" ";
}
cout<<endl;
return 0;
}