将多个向量(函数结果)组合到一个使用模板中
Combine multiple vectors (results of function) into one with template
我想在vector<T> v
和一个函数OP中具有模板功能,将T
映射到vector<U>
,并希望将f
应用于v
的每个元素向量的结果相结合至返回 vector<U>
= [OP(V [0](的元素,OP(V [1](...]的元素。
我发现的一个工作选项是在功能中添加一个示例以允许模板扣除:
template <typename Container>
Container& concat(Container& c1, Container const& c2) {
c1.insert(end(c1), begin(c2), end(c2));
return c1;
}
template <typename Container, typename UnaryOperation, typename U>
inline auto to_vec_from_vectors(Container& c, UnaryOperation&& op, U& ex)
-> std::vector<U> {
std::vector<U> v;
for (auto& e : c) {
std::vector<U> opv = op(e);
concat(v, opv);
}
return v;
}
,但自然而然地,我只想使用两个参数产生相同的结果。我的尝试[用decltype(*std::begin(op(*std::begin(c))))
替换U
]:
template <typename Container, typename UnaryOperation, typename U>
inline auto to_vec_from_vectors(Container& c, UnaryOperation&& op, U& ex)
-> std::vector<decltype(*std::begin(op(*std::begin(c))))> {
std::vector<decltype(*std::begin(op(*std::begin(c))))> v;
for (auto& e : c) {
std::vector<decltype(*std::begin(op(*std::begin(c))))> opv = op(e);
concat(v, opv);
}
return v;
}
不幸的是,这没有编译。我还担心如果OP是复杂的方法浪费时间。
这给出了:
error: conversion from ‘std::vector<U>’ to non-scalar type ‘std::vector<const U&, std::allocator<const U&> >’ requested
error: forming pointer to reference type ‘const U&
...因此,它似乎与" const"有关。
如何纠正此变体?有更好的选择吗?
删除容器迭代器会产生参考(或const引用,如果容器是const(,这就是为什么decltype(*std::begin(op(*std::begin(c))))
根据编译器错误得出const U&
的原因(而不是U
(。p>您可以通过再次使用std :: remove_reference再次删除参考(或者,如果要删除const
和volatile
,std :: remove_cvref(,或者只是向矢量询问其实际存储的内容:<</p>
decltype(*std::begin(op(*std::begin(c))))
-> typename decltype(op(*std::begin(c)))::value_type
我已经继续前进并删除了不需要的U& ex
参数。
template <typename Container, typename UnaryOperation>
inline auto to_vec_from_vectors(Container& c, UnaryOperation&& op)
-> std::vector<typename decltype(op(*std::begin(c)))::value_type> {
std::vector<typename decltype(op(*std::begin(c)))::value_type> v;
for (auto& e : c) {
std::vector<typename decltype(op(*std::begin(c)))::value_type> opv = op(e);
concat(v, opv);
}
return v;
}
演示
您还可以通过命名decltype
的三重重复:
template <typename Container, typename UnaryOperation>
using applied_op_t = typename decltype(std::declval<UnaryOperation>()(*std::begin(std::declval<Container>())))::value_type;
相关文章:
- 我需要将多个函数组合为一个函数
- 我在C++中使用提升哈希函数将 3 个双精度组合成一个面临冲突的哈希
- 找到 x^n 的所有组合,并检查它们的总和是否等于一个不包括相同数字的数字
- 如何将这两个函数组合成一个实现?
- 在 c 中给定一个固定数的情况下,找到所有可能的加法和组合(给定一个总和,找到它的可能的加法和排列
- 如何将两个代码组合成一个函数?
- 如何组合一个宽字符字符串,中间插入一些空字符
- 在C++中将返回unique_ptr和shared_ptr的两个工厂方法组合为一个
- 如何简化代码并将开关组合成一个功能?
- 如何将数组的每个n个元素组合成一个元素
- 如果我们从每个 Y 向量中选择一个值,则 X 数字的每个组合都可能
- 将 libstdc++ 和其他函数组合到一个库中
- 组合理论的一个问题
- 在编译时将整数和分数部分宏组合成一个新的宏或双精度
- 如何将一个 while 循环与 for 循环组合在一起?
- 将多个向量(函数结果)组合到一个使用模板中
- 如何将多个可变参数模板元组类组合成一个类?
- C++ STL 下一个组合排列
- 从一个组合框中选择项目,然后从其他组合框中删除该项目
- 将组合框设置为另一个组合框的ID