jeudi 24 septembre 2020

Dereference list::end()

I was playing around with std::list. Similarly to other containers, std::list::end refers to the past-the-end element of a std::list (ref).

So, we would expect the below code to print 1, 2, 3, 4, 5 (which it does):

std::list<int> l { 1, 2, 3, 4, 5 };
for (auto it = l.begin(); it != l.end(); ++it)
{
    std::cout << *it << ", ";
}
std::cout << std::endl;

However, the second line of the second code snippet should not print 5, but it does:

std::cout << *l.begin() << std::endl;
std::cout << *l.end() << std::endl;

Output: 1 and 5.

Why? I'm using gcc 11 and C++11 (same for C++20 btw).

Aucun commentaire:

Enregistrer un commentaire