Why can't I do std::map.begin() + 1?

前端 未结 2 806
走了就别回头了
走了就别回头了 2020-12-16 01:03

I have a std::map, which I want to iterate over, starting at the second entry.

I can workaround this fine, but I\'m confused about why the \"obvious\" s

相关标签:
2条回答
  • 2020-12-16 01:20

    std::map iterators are bidirectional, thus they provide only ++ and -- operators, but not operator+, even if it is +1.
    You can use std::advance if you really need to simulate operator+, but that would result into sequence of increment being called for the iterator.

    0 讨论(0)
  • 2020-12-16 01:38

    std::map<T>::iterator is of the iterator-class bidirectional iterator. Those only have ++ and -- operators. +N and [] is only available for random access iterators (which can be found in e.g. std::vector<T>).

    The reason behind this is that adding N to a random access iterator is constant time (e.g. add N*sizeof(T) to a T*), whereas doing the same thing for a bidirectional iterator would require applying ++ N times.

    What you can do though (if you have C++11) is:

    std::map<int, int>::const_iterator pIterTwo = std::next(pSomeMap.begin(),1);
    

    which does the right thing for all iterator types.

    0 讨论(0)
提交回复
热议问题