-2

我在 VS Code 中遇到了forrange循环。它给了我错误:

期望一个';'

期待一个表达式

VS 代码 C++ 错误

   mp[0] = 10;
   mp[1] = 200;
   mp[2] = 3000;
   mp[3] = 40000;

   for (int id : mp) // error for ":" and ")"
   {
       std::cout << id << std::endl;
   }
4

2 回答 2

1

如果mpstd::map<int,int>那么你的for循环有错误的类型,它不仅仅是一个int,而是每个元素的键/值对。你可以使用

for (auto const& item : mp)
{
    std::cout << item.first << ' ' << item.second << std::endl;
}

哪里.first是关键,哪里是.second价值。

于 2021-07-22T15:32:23.883 回答
-2

谢谢你的回答,Cory,但问题仍然存在:

缺少显式类型(假定为“int”)[13,21]

引用变量“item”需要一个初始化器 [13,27]

期望一个表达式 [13,31]

{
    std::map<int, int> mp;
    mp[0] = 10;
    mp[1] = 200;
    mp[2] = 3000;
    mp[3] = 40000;

    for (auto const &item : mp) // error for "&" and ":" and ")"
    {
        std::cout << item.first << ' ' << item.second << std::endl;
    }
}

Visual Studio Code c++11 扩展警告 - OSX Macbook

于 2021-07-22T16:13:49.900 回答