Building a matrix with a specific dimension

Hi there,

I would like to initialize a N-dimensional matrix by specifying the dimension N.
To be clearer :

if N=2 I use to do that :
std::vector<std::vector<double>> myMatrix;
if N=3 :
std::vector<std::vector<std::vector<double>>> myMatrix;
and so on...

What I would like is to give N as an argument of a function which construct a N-dimensional empty matrix.
Is that possible ?

Thank you.

Regards,
C.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <vector>
#include <typeinfo>
#include <iostream>

template<typename T, std::size_t N>
struct md_vector
{
    using type = std::vector<typename md_vector<T, N - 1>::type>;
};

template<typename T>
struct md_vector<T, 1>
{
    using type = std::vector<T>;
};

template<typename T, std::size_t N>
using md_vector_t = typename md_vector<T, N>::type;

int main()
{
    md_vector_t<int, 2> foo;
    //check if type is what we want:
    std::cout << (typeid(foo) == typeid(std::vector<std::vector<int>>));
}
1

http://coliru.stacked-crooked.com/a/6811f898decd0de0

What I would like is to give N as an argument of a function which construct a N-dimensional empty matrix.
Is that possible ?
Yes, it is poosible, but you will have to code class implementng it yourself.
Last edited on
Thank you for your reply. Seems crystal clear.
Topic archived. No new replies allowed.