jeudi 8 décembre 2022

The behavior of std::advance at the end of std::list

#include <iostream>
#include <list>
using namespace std;

int main() {
  list<int> A;
  A.push_back(1);
  A.push_back(2);
  A.push_back(3);

  auto it = A.begin();
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
  advance(it, 1);
  cout << *it << ' ';
}

I belive that list is a double linked list. Surprisingly, the output is 1 2 3 3 1. Can someone explain what's happening here? Here are questions:

  1. When we advance twice, we are at the node with 3. Here, an additional advance moves the iterator to A.end(). I believe that A.end() is an imaginary node that does not point to the original element. However, it prints out 3. Why?
  2. How come it prints out 1 at the end? The list is not a circular queue.

Aucun commentaire:

Enregistrer un commentaire