map/set iterator not derefencable

here is my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void print_words (const map <string, int>& printMap)
{
	FOO p (printMap.size()); //create an FOO object p
	p = for_each (printMap.begin(), printMap.end(), p);//call p for_each element in the map
	

	map <string, int>::const_iterator pos;
	
	for (pos = printMap.begin(); pos != printMap.end(); pos++)
	{
	cout << left << setw(ITEM_W) << pos->first << right << ":  " << pos->second;
	++pos;
	cout << "    " << left << setw(ITEM_W) << pos->first << right << ":  " << pos->second;
	}

	
}


Here is the error: "Debug assertion failed. Map/set iterator not derefencable."

I think I understand the problem: that I'm using my pos to iterator to the next map element and I'm using it with the printMap.end () function. However, I'm not sure how to get my program to do what I want, which is so output like this using a for loop, but with each iteration on the same line rather than a new line:

word : 1 word2 :1 word3: 2

Please let me know if you need anymore information. Thank you so much for the help!
closed account (o3hC5Di1)
Hi there,

All you need is to add a newline break at the end of your std::cout:

1
2
3
4
5
6
7
8
9
10
11
12
13
void print_words (const map <string, int>& printMap)
{
	FOO p (printMap.size()); //create an FOO object p
	p = for_each (printMap.begin(), printMap.end(), p);//call p for_each element in the map
	

	map <string, int>::const_iterator pos;
	
	for (pos = printMap.begin(); pos != printMap.end(); pos++)
	{
	     cout << left << setw(ITEM_W) << pos->first << right << ":  " << pos->second  << std::endl;
	}
}


Hope that helps.

All the best,
NwN
take a look at line 12
I am still getting the error even after I put the newline. ne555 i know line 12 is what's causing the problems, just not sure how to get the result i need if I remove it.
1
2
3
4
5
6
7
8
int count = 1;
	for (pos = printMap.begin(); pos != printMap.end(); pos++)
	{
	     cout << left << setw(ITEM_W) << pos->first << right << ":  " << pos->second;
	     if(count % 2)
	     	cout << endl;
	     ++count;
	}
Last edited on
Thanks for the help, but this is still not working. It prints this output:
1
2
3
100  :1
a  :8
about  :4


but I need it to print like this:
100 :1 a :8 about :4
1
2
3
4
for (pos = printMap.begin(); pos != printMap.end(); pos++)
{
	 cout << left << setw(ITEM_W) << pos->first << right << ":  " << pos->second << "    ";
}


Or maybe http://ideone.com/n8Hfg8
Last edited on
Thanks everyone, this helped a lot and I got it to work.
Topic archived. No new replies allowed.