Testing whether an iterator points to the last item?

前端 未结 9 924
旧巷少年郎
旧巷少年郎 2020-12-23 11:31

I have an stl iterator resulting from a std::find() and wish to test whether it is the last element. One way to write this is as follows:

mine *match = some         


        
9条回答
  •  既然无缘
    2020-12-23 12:28

    If you do:

    if(itr != Mine.end() && itr == --Mine.end())
    

    It should be fine. Because if itr is not at the end then there must be at least 1 element in the container and so end must yield a value result when decremented.

    But if you still don't like that, there are lots of ways to do something equivalent, as all the other answers show.

    Here's another alternative:

    if(itr != Mine.end() && std::distance(Mine.begin(), itr) == Mine.size()-1)
    

提交回复
热议问题