我这里有问题。我想在decltype
循环中使用range-for
来使用多维数组:
int a[][4]{
{0, 1, 2, 3 },
{4, 5, 6, 7 },
{8, 9, 10, 11}
};
for (auto& row : a) { // reference is needed here to prevent array decay to pointer
cout << "{";
for (auto col : row)
cout << col << ", ";
cout << "}" << endl;
}
decltype (*a) row{ *a};
cout << sizeof(row) << endl;
cout << typeid(row).name() << endl;
// for (decltype(*a) row : *a) {
// for (int col : row)
// cout << col << ", ";
// cout << endl;
// }
使用auto
我可以很容易地遍历数组但是使用decltype
它对我不起作用。
如果我取消注释代码,我得到的是:cannot convert from int to int(&)[4]
。
这是因为for(decltype(*a) row : *a)
线不正确。尝试正确读取:对于每个4个int的数组,而不是来自* a。
代码可能如下所示:
for (decltype(*a) row : a) {
for (int col : row)
cout << col << ", ";
cout << endl;
}
decltype
解引用(* a)将产生4个整数的数组。所以类型是int[4]
。与使用关键字auto
不同,它产生int*
。