如何获得嵌套向量的维度(嵌套)(不是大小)?

Ant*_*llo 31 c++ vector

请考虑以下声明:

vector<vector<int> > v2d;
vector<vector<vector<string>> > v3d;
Run Code Online (Sandbox Code Playgroud)

如何在后续代码中找出向量的"维度"?例如,v2d为2,v3d为3?

Bat*_*eba 57

这些方面的东西:

template<class Y> 
struct s
{
    enum {dims = 0};
};

template<class Y>
struct s<std::vector<Y>>
{
    enum {dims = s<Y>::dims + 1};
};
Run Code Online (Sandbox Code Playgroud)

然后例如,

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

具有吸引力的特性,所有评估都在编译时.

  • 我更喜欢这个解决方案,它在编译时进行评估,更类似于"type_traits"方式. (2认同)
  • 您也可以添加对自定义分配器的支持 (2认同)

Nik*_*iki 18

你可以这样做:

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

旁注:此数量有时称为" 排名 ".

  • 这确实构成了一堆无用的临时工; 也许它可以改进 (4认同)