Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the dimensions (nestedness) of a nested vector (NOT the size)?

Tags:

c++

vector

Consider the following declarations:

vector<vector<int> > v2d; vector<vector<vector<string>> > v3d; 

How can I find out the "dimensionality" of the vectors in subsequent code? For example, 2 for v2d and 3 for v3d?

like image 787
Antonello Avatar asked Mar 09 '15 13:03

Antonello


2 Answers

Something on these lines:

template<class Y>  struct s {     enum {dims = 0}; };  template<class Y> struct s<std::vector<Y>> {     enum {dims = s<Y>::dims + 1}; }; 

Then for example,

std::vector<std::vector<double> > x; int n = s<decltype(x)>::dims; /*n will be 2 in this case*/ 

Has the attractive property that all the evaluations are at compile time.

like image 186
Bathsheba Avatar answered Sep 24 '22 19:09

Bathsheba


You could do something like this:

template<typename T> int getDims(const T& vec) {    return 0; } template<typename T> int getDims(const vector<T>& vec) {    return getDims(T{})+1; } 

Sidenote: This quantity is sometimes called "rank".

like image 27
Niki Avatar answered Sep 22 '22 19:09

Niki