9

我知道在 C++ 中,您可以通过以下方式获得包含行和列的数组:

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

但是有没有更好的方法来做到这一点?

4

2 回答 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;
于 2013-02-10T08:15:23.640 回答
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
于 2019-11-02T22:32:51.817 回答