Trying to write a method which deletes the first (lowest-keyed) N items from an std::map. Tried this:
void EraseNMapElements(const int numElementsToRemove){
const int originalSize = _map.size();
auto eraseIter = _map.begin();
std::advance(eraseIter, numElementsToRemove);
_map.erase(_map.begin(), eraseIter);
assert(_map.size() == (originalSize - numElementsToRemove)) || (0 == originalSize) || (0 == _map.size()));
}
It works when the number of elements is more than the number requested to be removed. So if I had five elements, request to delete 2, the last 3 element remain. However, if I have one element and request to erase 2, I still have one element remaining.
Is there a neat way to cover this? I could shove an IF statement around checking for numElementsToRemove greater than map.size() but there must be a better solution?
std::advance(i, n)
has a precondition thati
can be incremented at leastn
times. In your code, you're not checking that precondition, so if you call it withnumElementsToRemove > originalSize
, you're violating that precondition and thus experiencing Undefined Behaviour. To fix that, you must do the check before callingstd::advance
, perhaps usingstd::min
: