在C++中查找二维数组的行数和列数

9

我知道在 C++ 中可以使用以下方法获取数组的行数和列数:

 int rows = sizeof array / sizeof array[0];
 int cols = sizeof array[0] / sizeof array[0][0];

然而,有没有更好的方法来做到这一点呢?

1
是的。由于这是 C++,请使用 vector - StoryTeller - Unslander Monica
2个回答

6
在C++11中,你可以使用模板参数推断来实现此操作。似乎extent type_trait已经存在于此目的。
#include <type_traits>
// ...
int rows = std::extent<decltype(array), 0>::value;
int cols = std::extent<decltype(array), 1>::value;

0

你也可以使用sizeof()函数;

int rows =  sizeof (animals) / sizeof (animals[0]);
int cols = sizeof (animals[0]) / sizeof (string);

例子:

#include <iostream>

using namespace std;

void sizeof_multidim_arrays(){
    string animals[][3] = {
        {"fox", "dog", "cat"},
        {"mouse", "squirrel", "parrot"}
    };
    int rows =  sizeof (animals) / sizeof (animals[0]);
    int cols = sizeof (animals[0]) / sizeof (string);
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            cout << animals[i][j] << " " << flush;
        }
        cout << endl;    
    }
}

输出:

fox dog cat 
mouse squirrel parrot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接