map/set iterators not incrementable error in C++

2019-04-14 18:11发布

问题:

When I execute the following code, I am getting map/set iterators not incrementable error.

typedef std::multimap<int, int> MapType;

assgnt::MapType my_map;
assgnt::MapType::iterator it;
for(it = my_map.begin(); it != my_map.end(); )
{
    my_map = obj1.addGoodNeighbours(it->first, it->second, my_map); 
    ++it;
}

Please help

回答1:

I don't know what a assgnt::MapType is, but assigning another assgnt::MapType to my_map inside the for loop, can't be a good thing:

my_map = obj1.addGoodNeighbours(it->first, it->second, my_map); 

You should at least reassign the iterator:

for(it = my_map.begin(); it != my_map.end(); ++it;) {
    my_map = obj1.addGoodNeighbours(it->first, it->second, my_map); 
    it = my_map.begin();
}

But i believe that code is far from correct. You are basically destroying the structure that you're iterating while iterating it.

EDIT: Well we do know what a MapType is now. All of the above is still correct. You can't just re-assign your maps while iterating them.



回答2:

You are modifying a map while you are iterating on it. This is not supported by std containers and as such is a bug in your program. Currently you are completely overwriting the object but more in details even adding elements is not supported.

You are getting this error probably because you are in debug mode and I would not be surprise if that would just crash in production.

To achieve the same effect you could use a temporary map:

assgnt::MapType my_map;
assgnt::MapType tmp;

for (auto it = my_map.begin(); it != my_map.end(); ++it) {
     // you need to change addGoodNeighboors to add elements in place instead of creating a new map
     obj1.addGoodNeighbours(tmp, it->first, it->second, my_map);  
}

my_map.insert(begin(tmp), end(tmp));


标签: c++ map iterator