c ++:将向量转换为元组

时间:2015-02-09 13:14:50

标签: c++ c++11 tuples

如何将std :: vector转换为std :: tuple? 我有

class T { };
int cnt = 3;
vector<T*> tv;
for (int i = 0; i < cnt; ++i) {
  tv.push_back(new T());
}

我想要

auto tp = std::tie(*tv[0], *tv[1], *tv[2]);

我怎样才能得到这个? 如果cnt足够大,我不能手动写这个tp。

  std::vector<
  ConvConnection<
  decltype(inputLayer),
  decltype(*C1[0]),
  decltype(*Conn1Opt[0]),
  RandomInitialization<arma::mat>,
  arma::mat
  >* > Conn1(6);

  for (size_t i = 0; i < 6; ++i) {
    Conn1.push_back(new  ConvConnection<
                    decltype(inputLayer),
                    decltype(*C1[0]),
                    decltype(*Conn1Opt[0]),
                    RandomInitialization<arma::mat>,
                    arma::mat
                    >(inputLayer, *C1[i], *Conn1Opt[i], 5, 5));
  }

这是代码。这里只有6,但我还需要一些大小超过100的向量。我需要将这个向量转换为元组。

3 个答案:

答案 0 :(得分:15)

通常,您无法将vector转换为tuple。但是,如果您尝试做的只是为某个<f(0), f(1), ..., f(N-1)>生成一个常量表达式的元组N,那么这对于索引序列技巧是可行的:

template <typename F, size_t... Is>
auto gen_tuple_impl(F func, std::index_sequence<Is...> ) {
    return std::make_tuple(func(Is)...);
}

template <size_t N, typename F>
auto gen_tuple(F func) {
    return gen_tuple_impl(func, std::make_index_sequence<N>{} );
}

我们可以使用:

// make a tuple of the first 10 squares: 0, 1, 4, ..., 81
auto squares = gen_tuple<10>([](size_t i){ return i*i;});

对于您的具体用例,即:

auto connections = gen_tuple<6>([&](size_t i) {
    return new ConvConnection<
                decltype(inputLayer),
                decltype(*C1[0]),
                decltype(*Conn1Opt[0]),
                RandomInitialization<arma::mat>,
                arma::mat
                >(inputLayer, *C1[i], *Conn1Opt[i], 5, 5);
});

答案 1 :(得分:10)

如果你有C ++ 14,你可以这样做:

template <typename T, std::size_t... Indices>
auto vectorToTupleHelper(const std::vector<T>& v, std::index_sequence<Indices...>) {
  return std::make_tuple(v[Indices]...);
}

template <std::size_t N, typename T>
auto vectorToTuple(const std::vector<T>& v) {
  assert(v.size() >= N);
  return vectorToTupleHelper(v, std::make_index_sequence<N>());
}

感谢自动扣除,这没关系。在C ++ 11中,没有自动扣除,您必须编写尾随decltype的返回类型。您还必须实现自己的index_sequence

答案 2 :(得分:7)

你不能。因为向量大小在运行时是已知的,但必须在编译时知道tuple类型(包括其大小)。