我想编写一个 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/