C++ VS Code on OSX forrange loop

228 Views Asked by At

I'm stuck with forrange loop in VS Code. It gives me error:

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;
   }
2

There are 2 best solutions below

1
On BEST ANSWER

Thank you for answer, Cory but problem still there:

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

0
On

If mp is std::map<int,int> then your for loop has the wrong type, it is not just an int, rather it is the key/value pair for each element. You could use

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

where .first is the key and .second is the value.