Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading