Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the value of std::list<T>::end() change after modifying list?

I'm trying to make use of the fact that iterators to lists remain valid after insertions and removals (except iterators to what you just removed). Is this also true of std::list<T>::end();

Suppose I try the following:

typedef std::list<int> list_int;

list_int myList;
list_int::iterator iter = myList.end();

myList.push_back(1);
myList.push_back(2);
myList.push_back(3);

if(iter == myList.end()) {
    /* do things here */
} else {
    /* do different things here */
    /* I don't expect this branch to ever execute */
}

This is important because elsewhere I might store a collection of iterators into this list, and I would test for validity by comparing against myList.end(). It's important that invalid iterators remain so even after insertions and removals.

like image 417
Filipp Avatar asked Oct 26 '12 02:10

Filipp


People also ask

How do I add items to the end of a list in C++?

Using push_back() : push_back() is used to insert the element at the end of list.

How does std::list work?

The std:list allows you to insert and remove items from anywhere. The std::list is implemented as a doubly-linked list. This means list data can be accessed bi-directionally and sequentially. The Standard Template Library list doesn't support fast random access, but it supports sequential access from all directions.

Is std::list doubly-linked?

std::list is a container that supports constant time insertion and removal of elements from anywhere in the container. Fast random access is not supported. It is usually implemented as a doubly-linked list.

Do lists exist in C++?

What is the C++ List? A list is a contiguous container, while a vector is a non-contiguous container. This means that a list stores its elements in contiguous memory, while a vector does not.


1 Answers

The value of std::lists end iterator never changes during the lifetime of the list. It is always valid, always the same and always corresponds to the imaginary "past the end" element of the list. This means that the value of some_list.end() memorized at any point in the list's lifetime will always be the same as the value of some_list.end() at any other point of its lifetime.

The language specification doesn't state it explicitly. However, there's simply no valid operation on the list that would invalidate the end iterator or associate its value with some other location.

In your example the second branch of that if will never execute.

If I'm not missing anything, the same is true for std::map and std::set as well.

like image 183
AnT Avatar answered Nov 15 '22 14:11

AnT