首页 > 解决方案 > 为什么我不能在 range-for 中使用 decltype 和多维数组?

问题描述

我这里有问题。我正在尝试decltyperange-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].

标签: c++11for-loopmultidimensional-arraydecltype

解决方案


那是因为线路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]。不像使用关键字autowhere 它会产生int*.

推荐阅读