C ++: convert vector to tuple

How to 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()); } 

I want to receive

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

How can I get this TP? If cnt is big enough, I cannot 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)); } 

This is the code. There are only 6 here, but I also need a vector whose size exceeds 100. I need to convert this vector to a tuple.

+6
source share
3 answers

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

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

What we can use as:

 // 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, this will 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); }); 
+13
source

You just can't. Since the size of the vector is known at run time, but the type of tuple (which includes its size) must be known at compile time.

+7
source

If you have C ++ 14, you can do it like this:

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

Thanks to automatic deduction, this is normal. In C ++ 11, without automatic subtraction, you need to write return types with a final decltype . You must also implement your own index_sequence .

+7
source

Source: https://habr.com/ru/post/982206/


All Articles