I'm currently debugging some code and am confused as to how the following is possible:
void DoSomething(int cell, const std::multimap<int, const Foo*>& map) {
auto range = map.equal_range(cell);
if (range.first != map.end()) {
int iterated = 0;
for (auto iter = range.first; iter != range.second; ++iter) {
iterated++;
}
assert(iterated > 0);
}
}
based on my understanding of std::multimap
this assertion should in any case always pass, yet it fails sometimes with iterated = 0.
Under what circumstances can this be possible?
Ok I figured it out.
I was under the wrong assumption that equal_range()
would return end()
as the first iterator if the multimap does not contain the requested key, but that's not correct.
If the multimap does not contain any elements for a certain key, it does not return map.end() for the first iterator, but instead it returns an iterator to the first element with a key Not Less
than the requested key. So, if the multimap doesn't contain the key requested, if (range.first != map.end())
will still pass, since both the first as well as the second iterator will both point to the element with the next larger key, but then there will be no iteration.