C++如何将函数应用于 vector 元素

标签 c++ c++11 templates vector transform

我想编写一个 C++ 函数来对 vector 应用 (lambda) 函数并返回另一个相同大小的 vector :

template <class T, class UnaryOperator>
T transform_vector(const T& input, UnaryOperator op)
{
    T output;
    std::transform(input.begin(), input.end(), std::back_inserter(output), op);
    return output;
}

如果函数 op 返回类型与 T 相同,则此代码有效。有没有办法告诉编译器输出 vector 的类型与 op 的返回函数相同,以使此代码在一般情况下工作?

最佳答案

there is way to tell the compiler that the type of the output vector is the same as the return function of the op to make this code work in general case?

-- 编辑-- std::decay<>在 Barry 的评论之后系统地添加(谢谢!)

我想是这样的(如果你可以使用 C++14)

template <class T, class UnaryOperator>
auto transform_vector(const T& input, UnaryOperator op)
{
    std::vector<std::decay_t<decltype(op(*input.begin()))>> output;
    std::transform(input.begin(), input.end(), 
                   std::back_inserter(output), op);
    return output;
}

对于 C++11 来说有点复杂(和冗余),因为您不能简单地使用 auto作为返回类型

template <class T, class UnaryOperator>
auto transform_vector(const T& input, UnaryOperator op)
   -> std::vector<typename std::decay<decltype(op(*input.begin()))>::type>
{
    std::vector<typename std::decay<decltype(op(*input.begin()))>::type>
       output;
    std::transform(input.begin(), input.end(), 
                   std::back_inserter(output), op);
    return output;
}

另一种方法,从 C++11 开始工作并避免冗余,传递具有默认值的第三个模板类型参数。

有点复杂,但我(恕我直言)更有趣,因为允许通过 decltype() 避免自动扣除并施加不同的返回类型。

template <typename T, typename UO,
   typename RetV = std::vector<typename std::decay<decltype(std::declval<UO>()
                                        (*std::declval<T>().begin()))>::type>>
RetV transform_vector (T const & input, UO op)
{
    RetV output;
    std::transform(input.begin(), input.end(), 
                   std::back_inserter(output), op);
    return output;
}

这也适用于 C++11。

从 C++14 开始,您可以使用 std::decay_t<T> 进行简化而不是 typename std::decay<T>::type .

关于C++如何将函数应用于 vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48655144/

相关文章:

c++ - 函数模板实例的地址可以作为函数指针传递给某个函数吗?

c++ - 在 C 回调中使用它时如何确保 "this"仍然有效?

c++ - 一个数的2个因数组成一组有多少种方法? (C/C++)

c++ - 具有已删除方法的 C++ 类是否可以轻松复制?

multithreading - std::mutex锁定功能和std::lock_guard <std::mutex>之间的区别?

c++ - 对于未实例化的模板,在 Clang 和 GCC 之间获得类似的行为?

c++ - 如何强制SFINAE选择第二个结构定义?

c++ - ubuntu 18.04 上的 gcc/g++ 7.3.0 链接错误

C++ VALGRIND 未初始化的值是由堆分配创建的

c++ - 关于如何识别 Rvalue 或 Lvalue 引用和 if-it-has-a-name 规则