Search code examples
c++stliterator

Arithmetic on end() iterator


Let A be a std::vector<double>,

Is this well-defined?

if(!A.empty())
    std::vector<double>::iterator myBack = A.end() - 1;

Is the end iterator only good for equalities and inequalities checks? Or I can perform some pointer arithmetic as long as I remain in the container?

On my platform this code works. I'm wondering if this is portable.


Solution

  • It is perfectly valid as vector::iterator is a random access iterator. You can perform arithmetic operations on it and it is not platform dependent.

    std::vector<double>::iterator it = A.end();
    while (it != A.begin()){
        --it; //this will skip A.end() and loop will break after processing A.front()
        //do something with 'it'
    }
    

    But A.end() refers to theoretical past-the-end element, so it does not point to an element and thus shall not be dereferenced. So best practice is to use reverse iterator instead of decrementing end iterator.

    for(std::vector<double>::reverse_iterator it = A.rbegin(); it != A.rend(); ++it) {
        //do something with 'it'
    }
    

    These two loops do the same thing, second is just understandable, cleaner way to do it.