c++11 - 为什么我不能在 range-for 中使用 decltype 和多维数组?
问题描述
我这里有问题。我正在尝试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)
不正确。尝试正确阅读:对于每个来自 a 的 4 个 int 数组,而不是来自 *a。
代码可能如下所示:
for (decltype(*a) row : a) {
for (int col : row)
cout << col << ", ";
cout << endl;
}
- 取消引用 (*a)
decltype
将产生一个由 4 个整数组成的数组。所以类型是int[4]
。不像使用关键字auto
where 它会产生int*
.
推荐阅读
- firebase - Firestore 安全规则 - 如何使用变量作为字段名称?
- php - Google Drive API 和 Google Drive 客户端错误
- php - array_merge 基于整数值
- html - 为什么我的弹性项目溢出它的弹性容器?
- c++ - 如何将 Mat H=findHomography 返回到 Matlab
- spring - 是否可以使用 Spring Boot 运行长时间的任务?
- ios - 错误代码“无法分配“无效”类型的值
- tfs - TFS On Premise:使用 Postman 创建待办事项的 API
- javascript - 如何以新键添加到键的相同嵌套格式提取嵌套对象的键
- angular - Angular 6 'mat-button-toggle' 不是已知元素