我这里有个问题。我尝试在range-for循环中使用decltype来使用多维数组:
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]。
发布于 2019-02-23 06:53:33
这是因为行for(decltype(*a) row : *a)是不正确的。尝试正确地读取它:对于来自a的每个4 int数组,而不是来自*a。
代码可能如下所示:
for (decltype(*a) row : a) {
for (int col : row)
cout << col << ", ";
cout << endl;
}decltype取消引用a (*a)将生成一个包含4个整数的数组。所以类型是int[4]。与使用生成int*.的关键字auto不同
https://stackoverflow.com/questions/54836274
复制相似问题