c++range-based-loop

Range based for loop iteration on std::map need for explanation


The following code is running properly

#include<iostream>
#include<map>
#include<algorithm>
#include<string>
#include<vector> using namespace std;

int main() {
    std::map<int, std::string> m;
    m[0] = "hello";
    m[4] = "!";
    m[2] = "world";
    for (std::pair<int, std::string> i : m)
    {
        cout << i.second << endl;
    }
    return 0; }

However, if I replace the for loop by

for (std::pair<int, std::string>& i : m)
{
    cout << i.second << endl;
}

is not working. I get 'initializing': cannot convert from 'std::pair<const int,std::string>' to 'std::pair<int,std::string> &' However,

for (auto& i : m)
{
    cout << i.second << endl;
}

is working, and also If I do the following

for (float& i : v)
{
    cout << i << endl;
}

I don't run into this problem. Why is that?


Solution

  • The key in map cannot be changed, so if you take key-value pair by reference key must be const.

    In your example int variable is a key, if you take pair by reference, you could modify that key, which cannot be done with map.

    Take a look at map::value type: https://en.cppreference.com/w/cpp/container/map.