STL算法 | std::transform函数,将给定范围内的数据按照某种操作后保存在另一个同种类型容器中。

transform定义于头文件 <algorithm>,应用给定的函数到范围并存储结果于始于 d_first 的另一范围。

函数原型

template< class InputIt, class OutputIt, class UnaryOperation >
constexpr OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
                              UnaryOperation unary_op );

template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation >
constexpr OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2,
                              OutputIt d_first, BinaryOperation binary_op );

参数

  • first1, last1 - 要变换的第一元素范围

  • first2 - 要变换的第二元素范围的起始

  • d_first - 目标范围的起始,可以等于 first1 或 first2

  • unary_op - 将要应用的一元算符函数。
    函数签名应等价于如下者:Ret fun(const Type &a);
    签名不必有 const & 。
    类型 Type 必须使得 InputIt 类型对象能在解引用后隐式转换到 Type 。 类型 Ret 必须使得 OutputIt 类型对象能被解引用并能被赋 Ret 类型值。​

  • binary_op - 被使用的二元函数对象。
    该函数的签名应当等价于:Ret fun(const Type1 &a, const Type2 &b);
    签名中并不需要有 const &。
    类型 Type1 与 Type2 必须使得 InputIt1 与 InputIt2 类型的对象在解引用后分别能隐式转换到 Type1 与 Type2 。 类型 Ret 必须使得 OutputIt 类型对象能被解引用并能被赋 Ret 类型值。​

返回值
指向最后一个变换的元素的输出迭代器。

可能的实现方式:

版本一
template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first, 
                   UnaryOperation unary_op)
{
    while (first1 != last1) {
        *d_first++ = unary_op(*first1++);
    }
    return d_first;
}
版本二
template<class InputIt1, class InputIt2, 
         class OutputIt, class BinaryOperation>
OutputIt transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, 
                   OutputIt d_first, BinaryOperation binary_op)
{
    while (first1 != last1) {
        *d_first++ = binary_op(*first1++, *first2++);
    }
    return d_first;
}

注:
std::transform 不保证按顺序应用 unary_op 或 binary_op 。为按顺序应用函数到数列,或应用修改序列元素的函数,应使用 std::for_each 。


测试用例

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>

int main()
{
	std::string s("hello");
	std::transform(s.begin(), s.end(), s.begin(),//	全部元素转换为大写
		[](unsigned char c) -> unsigned char { return std::toupper(c); });

	std::vector<std::size_t> ordinals;	// 将s中元素的ascii码值插入ordinals
	std::transform(s.begin(), s.end(), std::back_inserter(ordinals),
		[](unsigned char c) -> std::size_t { return c; });

	std::cout << s << ':';
	for (auto ord : ordinals) {
		std::cout << ' ' << ord;
	}

	// 下面语句的意思是:
	//     从[①, ② ) 范围开始,使用 ⑤ 操作,依次加上 从[③, ...) 开始的
	//     结果输出到 ④ 中 
	//
	//              ①                  ②               ③
	std::transform(ordinals.cbegin(), ordinals.cend(), ordinals.cbegin(),
		ordinals.begin(), std::plus<>{});
	//			    ④         ⑤

	std::cout << '\n';
	for (auto ord : ordinals) {
		std::cout << ord << ' ';
	}
	std::cout << '\n';
}

/*  输出结果
	HELLO: 72 69 76 76 7
	144 138 152 152 158
*/

补充几个可以用于此函数的函数对象:

  • plus: 加法函数对象类(类模板)
    int first[] = { 1,2,3,4,5 };
    int second[] = { 10,20,30,40,50 };
    int results[5];
    std::transform(first, first + 5, second, results, std::plus());
    // 两数组元素相加,存储在results中,11 22 33 44 55
  • minus: 减法函数对象类(类模板)
    int first[] = { 1,2,3,4,5 };
    int second[] = { 10,20,30,40,50 };
    int results[5];
    std::transform(first, first + 5, second, results, std::minus());
    // 两数组元素相减,存储在results中,-9 -18 -27 -36 -45
  • multiplies: 乘法函数对象类(类模板)
    int first[] = { 1,2,3,4,5 };
    int second[] = { 10,20,30,40,50 };
    int results[5];
    std::transform(first, first + 5, second, results, std::multiplies());
    // 两数组元素相乘,存储在results中,10 40 90 160 250
  • divides: 除法函数对象类(类模板)
    int first[] = { 10,40,90,40,10 };
    int second[] = { 1,2,3,4,5 };
    int results[5];
    std::transform(first, first + 5, second, results, std::divides());
    // // 两数组元素相除,存储在results中,10 20 30 10 2
  • modulus: 计算除法余数的函数对象类(类模板)
    int numbers[] = { 1,2,3,4,5 };
    int remainders[5];
    //std::transform(numbers, numbers + 5, remainders, std::bind2nd(std::modulus(), 2));
    // 注:binder2nd等函数在C++17以后就已经被弃用了,实现与上面同等功能的语句还可以用匿名函数实现
    std::transform(numbers, numbers + 5, remainders,
    [](int val) {return val % 2; });
    // 将奇数变成 1, 偶数变成 0 , 结果 1 0 1 0 1
  • equal_to: 用于相等比较的函数对象类(类模板)
    int foo[] = { 10,20,30,40,50 };
    int bar[] = { 10,20,40,80,160 };
    bool res[5];
    std::transform(foo, foo + 5, bar, res, std::equal_to());
    // 两数组对应项比较,结果存储在results中,true true false false false
  • negate: 负函数对象类(类模板)
    int numbers[] = { 10,-20,30,-40,50 };
    std::transform(numbers, numbers + 5, numbers, std::negate());
    // 将数字取反, -10 20 -30 40 -50
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我叫RT

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值