0
The Std::list class creates a circular list. When I create an iterator to go through it I come across an ambiguous situation, which I exemplify:
#include<iostream>
#include<list>
using namespace std;
int main()
{
list<int> lista;
lista.push_back(3);
lista.push_back(6);
lista.push_back(9);
list<int>::iterator it;
it=lista.begin();
for(int i=0;i<10;i++)
{
cout << (*it);
it++;
}
return 0;
}
In this case we will get the following output:
3693369336
That is, in the last position if I advance I will stop at the node "end" which, from what I understand is again the first on the list. There is another way to avoid this repetition of the last/first (a kind of header node) in order to traverse the list circularly without walking with additional conditions?
Where did you read that
std::list
is circular?– Mário Feroldi
I may have confused bidirectional with circular now that you ask!
– gtpt
It was from here: http://www.cplusplus.com/reference/list/list/begin/
– gtpt
Deliberately exceeding the end of the list causes undefined behavior (UB). The looping should go up to
lista.size()
orlista.end()
(depending on the type of looping)– Gomiero
Adding to what has already been said, the values you see are mere chance of the current implementation, which from what I have tested, all compilers have. Even so, it is undefined behavior as already said
– Isac
@gtpt, an iterator being bidirectional means it can be incremented and decremented.
– Mário Feroldi
Yes I had already realized. It was the random values that Isac refers to that confused me.
– gtpt