I have a global variable as a map
and a function that iterates over the elements of this map
such as:
void printMap(){
for ( auto it = MyMap.begin(); it != MyMap.end(); ++it ){
std::cout << it->second;
}
}
which works fine.
I want to add a functionality to the function which is after printing an element, it should be erased from the map
like this:
void printMap(){
for ( auto it = MyMap.begin(); it != MyMap.end(); ++it ){
std::cout << it->second;
MyMap.erase(it);
}
}
However, by adding the erase line I got an exception error of this type:
Thread 2: EXC_BAD_ACCESS (code=1, address=0x20000002)
I tried another way which is like this:
void myFunction(){
printMap();
MyMap.clear();
}
but I also got the same exception
Thread 2: EXC_BAD_ACCESS (code=1, address=0x0)
As I understand this kind of exception occurs when we refer to a memory location that does not exist. But I know it is there since the iterator got its value and it was printed. Even so I used the second method just in case that I don't refer to non-existing memory location but still I'm getting the exception.
So how can I iterate over the elements print the result then erase it?
UPDATE1
following the suggestions below and the linked topic I changed my function into this:
void printMap(){
bool i = true;
for (auto it = MyMap.cbegin(), next_it = MyMap.cbegin(); it != MyMap.cend(); it = next_it)
{
cout << it->second;
next_it = it; ++next_it;
if (i) {
MyMap.erase(it);
}
}
}
I have also tried this https://stackoverflow.com/a/42820005/7631183 and this https://stackoverflow.com/a/42819986/7631183
The problem is still not solved and I'm getting the same error
UPDATE2
I run the same exact code on a different machine and it worked fine. I still don't know what is the reason so I would guess as suggested in the comments that std::map
on the first had some problems.
P.S. The first machine was a mac and the second was a Linux