Testing whether an iterator points to the last item?

前端 未结 9 923
旧巷少年郎
旧巷少年郎 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:25

    Do this:

    // defined in boost/utility.hpp, by the way
    template 
    Iter next(Iter iter)
    {
        return ++iter;
    }
    
    // first check we aren't going to kill ourselves
    // then check if the iterator after itr is the end
    if ((itr != Mine.end()) && (next(itr) == Mine.end()))
    {
        // points at the last element
    }
    

    That is all. Never gives you undefined behavior, works on all iterators, good day.

    Wrap it up for fun:

    template 
    bool is_last(Iter iter, const Cont& cont)
    {
        return (iter != cont.end()) && (next(iter) == cont.end())
    }
    

    Giving:

    if (is_last(itr, Mine))
    

    If you're allergic to utility functions/nice looking code, do:

    if ((itr != Mine.end()) && (itr + 1 == Mine.end()))
    

    But you can't do it on non-random-access iterators. This one works with bidirectional iterators:

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

    And is safe since end() > itr by the first check.

提交回复
热议问题