为什么我不能在范围中使用decltype - 用于多维数组?

问题描述 投票:2回答:1

我这里有问题。我想在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]

c++11 for-loop multidimensional-array decltype
1个回答
3
投票

这是因为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*
© www.soinside.com 2019 - 2024. All rights reserved.