std库学习①:transform

std::transform在指定的范围内应用于给定的操作,并将结果存储在指定的另一个范围内。要使用std::transform函数需要包含<algorithm>头文件。

以下是std::transform的两个声明,一个是对应于一元操作,一个是对应于二元操作:

template <class InputIterator, class OutputIterator, class UnaryOperation>
  OutputIterator transform (InputIterator first1, InputIterator last1,
                            OutputIterator result, UnaryOperation op);
	
template <class InputIterator1, class InputIterator2,
          class OutputIterator, class BinaryOperation>
  OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
                            InputIterator2 first2, OutputIterator result,
                            BinaryOperation binary_op);
  • 一元操作

template <class InputIterator, class OutputIterator, class UnaryOperation>
  OutputIterator transform (InputIterator first1, InputIterator last1,
                            OutputIterator result, UnaryOperation op);

该函数旨在将[first1,last1)【左闭右开】这一段内容复制写入result中,并且是在对迭代器遍历的每一个元素进行op的操作后才写入result中。

如op的一个实现 即将[first1, last1]范围内的每个元素加5,然后依次存储到result中。

int add_(int i){ return i + 5; }

实际使用如下:

std::transform(temp.begin(),temp.end(),result,add_);

亦可以使用lamda表达式:

std::transform(temp.begin(),temp.end(),result,[](int i){ return i + 5; });
  • 二元操作

template <class InputIterator1, class InputIterator2,
          class OutputIterator, class BinaryOperation>
  OutputIterator transform (InputIterator1 first1, InputIterator1 last1,
                            InputIterator2 first2, OutputIterator result,
                            BinaryOperation binary_op);

使用[first1, last1]范围内的每个元素作为第一个参数调用binary_op,并以first2开头的范围内的每个元素作为第二个参数调用binary_op,每次调用返回的值都存储在以result开头的范围内。给定的binary_op将被连续调用last1-first1+1次。binary_op可以是函数指针或函数对象或lambda表达式。

如binary_op的一个实现即将first1和first2开头的范围内的每个元素相加,然后依次存储到result中。

int add_(int, a, int b) { return a + b };

实际使用如下:

std::transform(temp.begin(),temp.end(),temp.begin(),result,add_);

同样可以使用lamda表达式,示例如一元操作。

 

  • 参考

C++/C++11中std::transform的使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值