STL iterator before std::map::begin()

前端 未结 3 2010
暖寄归人
暖寄归人 2021-01-12 01:33

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 i

3条回答
  •  [愿得一人]
    2021-01-12 02:17

    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.

提交回复
热议问题