Are such statements valid by the standard?
std::string str{"123"};
auto it = str.begin();
--it;
++it; // Does *it point to character '1' now?
I've tried this on g++ 4.7.2 and clang++ 3.5 - *it
returns '1'
.
Is this the standard behavior in c++11?
Operations Performed on the Iterators:Operator (*) : The '*' operator returns the element of the current position pointed by the iterator. Operator (++) : The '++' operator increments the iterator by one. Therefore, an iterator points to the next element of the container.
An iterator is used to point to the memory address of the STL container classes. For better understanding, you can relate them with a pointer, to some extent. Iterators act as a bridge that connects algorithms to STL containers and allows the modifications of the data present inside the container.
No, it is not valid.
It is undefined behaviour, as 24.2.6 [bidirectional.iterators] states that a postcondition of --it
is that the result must be dereferenceable. As it points before begin()
in your example, this condition is not met and hence the code is illegal.
As there is no diagnostic required it might seem to work, but you can not (and should not) rely on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With