Arithmetic pointer to end () iterator

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

Is this clearly defined?

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

Is the end iterator useful only for checking equality and inequality? Or can I do some pointer arithmetic while I stay in the container?

This code works on my platform. I wonder if it is portable.

+6
source share
2 answers

This is perfectly true since vector::iterator is a random access iterator. You can perform arithmetic operations on it, and it is platform independent.

 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 a theoretical A.end() element, therefore, it does not indicate the element and, therefore, should not be dereferenced. Therefore, it is best to use a reverse iterator instead of a decrementing final 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, the second is just a clear, cleaner way to do it.

+5
source

This is almost safe if you remember some exceptional cases:

A.end() gives you an iterator denoting a position only outside of std::vector . You should not try to dereference it.

If the vector has zero elements, then A.end() - 1 is not well defined. In all other cases, this is the case, and you can really do pointer arithmetic while you are within the container. Note that the standard ensures that std::vector data is contiguous and packaged in exactly the same way as a C ++ array of type contains. The one exception is std::vector<bool> , which behaves differently due to its specific packaging specialization. (Note that sizeof(bool) not guaranteed to have a specific meaning by standard).

If I were you, I would use A.rbegin() to access the A.rbegin() element and check the return value before continuing and stick to the iterator wording. It is too easy to forget the specialization std::vector<bool> .

+4
source

Source: https://habr.com/ru/post/975520/


All Articles