首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我不能在range-for的多维数组中使用decltype?

为什么我不能在range-for的多维数组中使用decltype?
EN

Stack Overflow用户
提问于 2019-02-23 06:50:20
回答 1查看 39关注 0票数 0

我这里有个问题。我尝试在range-for循环中使用decltype来使用多维数组:

代码语言:javascript
运行
复制
    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]

EN

Stack Overflow用户

发布于 2019-02-23 06:53:33

这是因为行for(decltype(*a) row : *a)是不正确的。尝试正确地读取它:对于来自a的每个4 int数组,而不是来自*a。

代码可能如下所示:

代码语言:javascript
运行
复制
for (decltype(*a) row : a) {
    for (int col : row)
        cout << col << ", ";
    cout << endl;
}

  • 使用decltype取消引用a (*a)将生成一个包含4个整数的数组。所以类型是int[4]。与使用生成int*.

的关键字auto不同

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54836274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档