'More concise way to declare high dimensional vector

I don't like how for example a 3 dimensional vector is called this way:

std::vector<std::vector<std::vector<value_type>>>

Not to mention if I would like to have 4 dimensional or even higher.

Is there any way to use perhaps template metaprogramming or some technique to be able to declare high dimension vector with higher readability?

For example to be able to declare an high dimensional vector like this (just an example):

t_vector<5, {10, 2, 2, 2, 2}, int> a;

and get a with capacity of [10][2][2][2][2].

Is it possible to do something like this? Or why if not?



Solution 1:[1]

You could use a typedef which just creates an alias for a type e.g.

typedef std::vector<std::vector<std::vector<int>>> iVector3d;

From now on you just use iVector3d instead of that big ugly thing and C++ will literally replace iVectord3 with the actual definition when you run the code so nothing else changes.

The draw back to this is that you have to specify the type, like as I've done with the int there. But the plus is that its super easy to use compared to templates.

Solution 2:[2]

Well, I think the solution from https://stackoverflow.com/users/8605791/llllllllll above does not solve the main case to std::vector.

As once you've tried to declare something like 'vec_builder<int, n, m>::build()', where the n or m is actually variable instead of constant.

Just try this (requires C++17 or higher):

template<class T, class... Args> auto multivector(size_t n, Args&&... args) {
  if constexpr (sizeof...(args) == 1) {
    return std::vector<T>(n, args...);
  } else {
    return std::vector(n, multivector<T>(args...));
  }
}
  • usage: auto g = multivector<long long>(n, m, 0);
  • equivalent: std::vector g(n std::vector<long long>(m));

btw this is my first post to stackoverflow... XD

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saman
Solution 2