1

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?

roi_saumon
  • 489
  • 4
  • 13
  • Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"* and you'll find plenty of SO related question for this. – Jason Sep 01 '22 at 13:47
  • 4
    C++ compilers have a well-earned reputation for emitting completely confusing and head-scratching error messages. This isn't the case here. The error message tells you, literally, what the problem is. – Sam Varshavchik Sep 01 '22 at 13:50

1 Answers1

5

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.

trokymchuk
  • 127
  • 7