Reputation: 1322
I am using boost 1.56 and have an unordered_map. When I insert a key value of zero as follows:
boost::unordered_map<int, int> map;
for(int i=0; i < size; i++)
{
int value = another_array[j];
map.insert(i, value);
}
I get a crash when accessing the map using map.at(0);
I've tested that the insert works by looking at the std::pairiterator, bool>
that the insert returns and the bool is true, indicating that it was successfully inserted I am creating a local to global numbering map so my keys are all 0:N-1. I know N and so should be able to loop over (count == 0:N-1) as follows:
for(int j=0; j < count; j++)
{
if(map.count(j))
printf("Value at index %d is %d\n", j, map.at(j));
}
but the count of k is zero. If I don't perform the check I get an out of bounds error. How can this be happening? If I switch to using 1-N as keys there is no such problem.
I do realise btw that in this example a map is slight overkill, but I have my reasons.
Note that I can not use std::unordered map as we are cross platform and our linux compiler doesn't currently support it.
Upvotes: 0
Views: 707
Reputation: 31
at doesn't take index as a parameter. It takes a key as parameter. If there is no item inserted with key "0", boost will throw exception which results in crash.
http://www.boost.org/doc/libs/1_48_0/doc/html/boost/unordered_map.html#id1601722-bb
Upvotes: 0
Reputation: 1322
Answer found thanks to sehe forcing me to write self contained code. This showed up an under allocation of an array further up, overwrites past the end of this were causing the normal memory wierdness and this was just a symptom.
Upvotes: 0
Reputation: 392911
Before edit: Most likely your hash<> specialization or equality comparison for key_type
is broken.
You don't show it, but only this kind of invariant-breaking error can explain the behaviour you describe (in a self-contained minimal example), as far as I can tell.
After edit: You should create a self-contained example that shows the error for you, for us to be able to come up with better diagnostics
Upvotes: 1