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的使用

发布了90 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_37160123/article/details/93712707
std
今日推荐