Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decreasing begin() iterator and then increasing it again

Tags:

c++

c++11

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?

like image 675
PovilasB Avatar asked Mar 14 '15 21:03

PovilasB


People also ask

What does iterator return c++?

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.

Why use iterator in c++?

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.


1 Answers

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.

like image 146
Daniel Frey Avatar answered Nov 14 '22 12:11

Daniel Frey