#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <functional>
//transform
int main()
{
/************************************************************************/
//transform
/************************************************************************/
//transform:
//版本1:将范围[first,last)通过搭配function obj对range内的对象进行某种运算,然后将返回值复制到另一个range中
//版本2:将范围[first,last)与[first2,first2+(last1-first1))内的元素进行function obj的运算,将结果复制到另一个range中
/*
template<class InputIterator, class OutputIterator, class UnaryFunction>
OutputIterator transform(
InputIterator _First1,
InputIterator _Last1,
OutputIterator _Result,
UnaryFunction _Func
);
*/
/*
template<class InputIterator1, class InputIterator2, class OutputIterator,
class BinaryFunction>
OutputIterator transform(
InputIterator1 _First1,
InputIterator1 _Last1,
InputIterator2 _First2,
OutputIterator _Result,
BinaryFunction _Func
);
*/
//测试版本1:
const int N = 7;
int arr[N] = { 4, -5, 6, -7, 1, 2, -3 };
std::vector<int> iv;
//如果运算是identity function,transform与copy相同
//4 -5 6 -7 1 2 -3
std::transform(std::begin(arr), std::end(arr),
std::back_inserter(iv), std::identity<int>());
std::copy(iv.begin(), iv.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
//-4 5 -6 7 -1 -2 3
std::transform(std::begin(arr), std::end(arr),iv.begin(), std::negate<int>());
std::copy(iv.begin(), iv.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
//测试版本2:在版本1的基础上增加一个output iterator,常用ostream_iterator
int b[N] = { 10, 9, 8, 7, 6, 5, 4 };
//6 14 2 14 5 3 7
std::transform(iv.begin(), iv.end(), std::begin(b),
std::ostream_iterator<int>(std::cout, " "), std::plus<int>());
std::cout << std::endl;
//b数组元素未发生变化
//10 9 8 7 6 5 4
std::copy(std::begin(b), std::end(b), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
//向量iv元素也未发生变化
//-4 5 -6 7 -1 -2 3
std::copy(iv.begin(), iv.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl; std::cout << std::endl;
return 0;
}
====================打个广告,欢迎关注====================
QQ: | 412425870 |
csdn博客: | http://blog.csdn.net/caychen |
码云: | https://gitee.com/caychen/ |
github: | https://github.com/caychen |
点击群号或者扫描二维码即可加入QQ群: | |