In C++11's std::map
, is there some valid iterator x such that ++x is guaranteed to equal map::begin()
? I would like to detect if a function I just called (mine) has walked an iterator off the front of a function. The function will move the iterator exactly one position backward.
Does the answer hold for the rest of the library?
No, iterators before the beginning in std
containers are all UB (except for reverse iterators, which will probably not solve your problem).
You probably need to fix the function in question. Failing that, wrap it and catch the bad behavior before you call it. Failing that, you could insert a negative infinity element into the map
key type ordering, and add a sentinal value. Failing that, you could write iterator adapters that wrap your map
iterators with ones that can go one-before-beginning without UB.
These are ordered in my order of recommendation, roughly. Each has ways it could fail, and they get more error prone and dangerous as my recommendation gets more remote.