OSX forrange 循环上的 C++ VS 代码

C++ VS Code on OSX forrange loop

我被 VS Code 中的 forrange 循环困住了。它给我错误:

expected a ';'

expected an expression

VS Code C++ error

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

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

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

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

其中 .first 是键,.second 是值。

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

explicit type is missing ('int' assumed) [13,21]

reference variable "item" requires an initializer [13,27]

expected an expression [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 extension warning - OSX Macbook