Re: Map losing elements!?
On Oct 2, 3:22 am, Sam <s...@email-scan.com> wrote:
Johannes Bauer writes:
I've been trying around with a simple std::map<mytype,
unsigned> for an hour now and can't find the bug. It is my
belief that I am missing something incredibly obvious...
please help me see it.
Scenario: I created the map and inserted some elements.
Afterwards I try to iterate over them:
std::map<mytype, unsigned int> values;
/* insert some values, say 5 */
/* this will then report 5 */
std::cerr << "cnt = " << values.size() << std::endl;
for (std::map<mytype, unsigned int>::iterator j = values.begin(); j !=
=
values.end(); j++) {
std::cerr << j->second << " -> ";
j->first.Dump();
std::cerr << std::endl;
}
However in the "for" loop, always only 2 items show up. I
figured something was wrong with my operator< - essentialy
"mytype" is just a container around a LENGTH byte unsigned
char[] array:
bool operator<(const mytype &Other) const {
for (unsigned int i = 0; i < LENGTH; i++) {
if (Other.Data[i] < Data[i]) return true;
}
return false;
}
Can anyone explain this behaviour?
Although your operator< does look wrong, this wouldn't really
explain your claimed problem. If there are 5 elements in the
map, then there are 5 elements in the plan.
It's undefined behavior. Consider an implementation which
maintains a dummy node for end, and a separate count for all
insertions. An error in the comparison operator could easily
cause the implementation to insert the node behind end, or
somewhere else it is no longer accessible. More generally, once
he has inserted an element using this comparison function,
anything goes.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34