简体   繁体   中英

map iterator not dereferencable

I am getting compile error "map/set" iterator not dereferencable". What is going on here?

#include<iostream>
#include<map>

using namespace std;

int main(){
    map<int, int> m;
    map<int, int>::iterator itr=m.begin();

    itr->first = 0;
    itr->second = 0;

    cout << itr->first << " " << itr->second;
    return 0;
}

The map is empty, so m.begin() is equal to the past-the-end iterator and is therefore invalid.

You first have to insert elements somehow (you can also do that implicitly by using operator[] ) to make it useful.

Also, you cannot modify the key of an element like this. You would have to remove ( erase ) the element from the map and insert a new one with the new key.

Here's an example about that:

#include<iostream>
#include<map>

using namespace std;

int main(){
    map<int, int> m;

    // insert element by map::insert
    m.insert(make_pair(3, 3));

    // insert element by map::operator[]
    m[5] = 5;

    std::cout << "increased values by one" << std::endl;
    for(map<int, int>::iterator it = m.begin(); it != m.end(); ++it)
    {
        it->second += 1;
        cout << it->first << " " << it->second << std::endl;
    }

    // replace an element:        
    map<int, int>::iterator thing = m.find(3);
    int value = thing->second;
    m.erase(thing);
    m[4] = value;

    std::cout << "replaced an element and inserted with different key" << std::endl;
    for(map<int, int>::iterator it = m.begin(); it != m.end(); ++it)
    {
        cout << it->first << " " << it->second << std::endl;
    }

    return 0;
}

Your map 's empty! What your iterator is pointing to is undefined.

What you wanted to do is

int main(){
    map<int, int> m;
    m[0] = 0;
    map<int, int>::iterator itr=m.begin();

    cout << itr->first << " " << itr->second;
    return 0;
}

Here you have not assign any value. and you can not change the key of itr->first of it. It can be read only. But you can edit itr->second .

map<int, int> m;
    m[10]=0;
    map<int, int>::iterator itr=m.begin();


      itr->second=10;
    cout << itr->first << " " << itr->second;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM