Std::Begin and Std::end iterators in the circular list context

Asked

Viewed 116 times

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?

  • 1

    Where did you read that std::list is circular?

  • I may have confused bidirectional with circular now that you ask!

  • It was from here: http://www.cplusplus.com/reference/list/list/begin/

  • 2

    Deliberately exceeding the end of the list causes undefined behavior (UB). The looping should go up to lista.size() or lista.end() (depending on the type of looping)

  • 2

    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

  • 1

    @gtpt, an iterator being bidirectional means it can be incremented and decremented.

  • Yes I had already realized. It was the random values that Isac refers to that confused me.

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.