Is there a way at runtime to find out how many dimensions a vector has? For example, vector<vector<int> > would be a two-dimensional vector (so this is diff. from its size() ). Is there any way to discover that at runtime?

Printable View

- 04-15-20086tr6trAny way to find out how many "dimensions" a vector has?
Is there a way at runtime to find out how many dimensions a vector has? For example, vector<vector<int> > would be a two-dimensional vector (so this is diff. from its size() ). Is there any way to discover that at runtime?

- 04-15-2008brewbuck
The drill_down function I posted earlier is easily adapted to do this.

Code:`template <typename T>`

int vector_dimensions(const T &)

{

return 0;

}

template <typename T>

int vector_dimensions(const vector<T> &)

{

return 1 + vector_dimensions(typename vector<T>::value_type);

}

- 04-15-20086tr6tr
- 04-15-2008brewbuck
I just realized my code has a bug in it. You do need a named parameter:

Code:`template <typename T>`

int vector_dimensions(const vector<T> &vec_p)

{

return 1 + vector_dimensions(vec_p[0]);

}

- 04-15-20086tr6tr
- 04-15-2008brewbuck
Well, doing this with functions forces you to pass in a specific instance, when it isn't really necessary (actually, it's not necessary for the function version either, but you'd have to specify the template parameter explicitly instead of letting the compiler deduce it from the argument). A metaprogram would be written with class templates instead of function templates:

Code:`template <typename T>`

struct vector_dimensions

{

static const int n = 0;

};

template <typename T>

struct vector_dimensions<vector<T> >

{

static const int n = 1 + vector_dimensions<T>::n;

};

The only downside is having to specify the type explicitly even if you DO have an object at hand. That can be addressed by pairing the vector_dimensions<> template with a small helper function:

Code:`template <typename T>`

int get_vector_dimensions(const T &vec_p)

{

return vector_dimensions<T>::n;

}

- 04-15-20086tr6tr