将多个向量(函数结果)组合到一个使用模板中

Combine multiple vectors (results of function) into one with template

本文关键字:一个 组合 向量 函数 结果      更新时间:2023-10-16

我想在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再次删除参考(或者,如果要删除constvolatile,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;