Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate over a map and calling a function that deletes other elements is the map

Tags:

c++

stl

i have a map which is defined in global memory. i'm iterating over it, let's say i'm in the 3rd element. now i'm calling another function that generates its own iterator over the same map, however it might erase the 4th or 5th ... elements in the map. my question is, when i return from that function and continue to iterate over the map (i remind you i'm in the 3rd element), can my iterator be invalid or is it safe?

sorry i can't attach the code it is very very long.

thanks

EDIT: my question is something like this:

map<string,string> mapi;

void er() {
    mapi.erase("t");
} 

int main() {


mapi.insert(pair<string,string>("w","a"));
mapi.insert(pair<string,string>("e","a"));
mapi.insert(pair<string,string>("r","a"));
mapi.insert(pair<string,string>("t","a"));
mapi.insert(pair<string,string>("A","a"));
mapi.insert(pair<string,string>("u","a"));
mapi.insert(pair<string,string>("C","a"));

map<string,string>::iterator it;
for (it=mapi.begin(); it!=mapi.end(); it++) {
    cout << it->first << endl;
    if (it->first=="t")
        er();
}

}

in this case i erase the same element - valgrind says its an error. however when i delete other elements it seems to work fine.

like image 273
Asher Saban Avatar asked Jun 05 '11 12:06

Asher Saban


1 Answers

From http://www.sgi.com/tech/stl/Map.html:

Erasing an element from a map also does not invalidate any iterators, except, of course, for iterators that actually point to the element that is being erased.

like image 194
Oliver Charlesworth Avatar answered Sep 25 '22 02:09

Oliver Charlesworth