gpt4 book ai didi

c++ - 重载 std::transform 算法

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:38:27 26 4
gpt4 key购买 nike

考虑 std::transform 算法的标准使用:

vector<int> in = { 1, 2, 3 };
auto f0 = [](int val) { return val + 1; };
auto f1 = [](int val) { return val > 1; };

vector<int> out0(in.size());
std::transform(in.begin(), in.end(), out0.begin(), f0);
vector<bool> out1(in.size());
std::transform(in.begin(), in.end(), out1.begin(), f1);

这很好用,但写起来很长。我想写这样的东西:

auto out0 = tranform(in, f0);
auto out1 = tranform(in, f1);

如何重载转换算法以允许这种语法?

最佳答案

下面应该做你想做的

#include <algorithm>
#include <iostream>
#include <type_traits>
#include <vector>

template<typename T, typename F>
std::vector<typename std::result_of<F(T)>::type>
transform(const std::vector<T>& l, F func)
{
typedef typename std::result_of<F(T)>::type FunctorReturnType;
std::vector<FunctorReturnType> out(l.size());
std::transform(l.begin(), l.end(), out.begin(), func);
return out;
}

int main ()
{
const std::vector<int> in{ 1, 2, 3 };
auto f0 = [](int val) { return val + 1; };
auto f1 = [](int val) { return val > 1; };

auto out0 = transform(in, f0);
auto out1 = transform(in, f1);

for (const auto& m: out0) std::cout << m << std::endl;
for (const auto& m: out1) std::cout << m << std::endl;
}

关于c++ - 重载 std::transform 算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22112978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com