user1950929
user1950929

Reputation: 874

c++ debug assertion failed: map/set iterator not dereferencable

I am getting the following debugging error:

Debug Assertion Failed!
Program: Path\To\vc\include\xtree
Line: 237

Expression: map/set iterator not dereferencable

whith these lines of code:

for(std::map<int,IO::ctcolor>::iterator it = IO::colorTable.begin(); it != IO::colorTable.end();) {
    //left out some code here, but even without it doesn't work
    cout << "dummy"; //gets printed multiple times while iterating, so the map is not empty
    ++it;
}

The for loop iterates through all elements of IO::colorTable but doesn't stop when reaching the end, I can see this when printing data to the console inside the loop.

Edit: I just noticed that the error occurs in the line after the for loop where I mistakenly tried to access it

Upvotes: 3

Views: 6537

Answers (1)

Ravid Goldenberg
Ravid Goldenberg

Reputation: 2299

I believe the problem is that you increment the value somewhere along the way without noticing, the error means you are trying to dereference the end() iterator.

Have a look at this code i believe it is pretty similar to yours and as you can see it worked fine.

#include <map>
#include <iostream>
using::std::map;
using::std::pair;

class IO
{
private:

class ctcolor
{
private: 
    char c;
public:
    ctcolor(char c){c='c';}
};

map<int,ctcolor> colorTable;
public:
IO(){
    for(int i=0;i<10;i++)
{
   colorTable.insert(pair<int,IO::ctcolor>(i,'c'));
}
}
void io(){
    for(std::map<int,IO::ctcolor>::iterator it = IO::colorTable.begin(); it != IO::colorTable.end();) {
std::cout << "dummy"; 
++it;}
}

};

int main()
{
IO io;
io.io();
return 0;
}

Upvotes: 3

Related Questions