c ++:将向量转换为元组 [英] c++ : convert vector to tuple

查看:189
本文介绍了c ++:将向量转换为元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I convert std::vector to std::tuple ? I have

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]);

如何获得此tp?
如果cnt足够大,我不能手动写这个tp。

How can I get this tp ? If cnt is big enough, I can't write this tp manually.

  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.我需要将这个向量转换为一个元组。

This is the code. Here is just 6, but I also need some vector whose size is over 100. I need to convert this vector to a tuple.

推荐答案

p>通常,您不能将向量转换为 tuple 。然而,如果你想做的是使元组< f(0),f(1),...,f(N-1)> 对于一些 N 这是一个常量表达式,那么可以用索引序列技巧:

Generally, you cannot convert a vector to a tuple. However, if all you're trying to do is make the tuple <f(0), f(1), ..., f(N-1)> for some N that is a constant-expression, then that is doable with the index sequence trick:

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;});

对于您的特定用例,将是:

For your specific use-case, that would be:

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);
});

这篇关于c ++:将向量转换为元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆