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.
Using push_back() : push_back() is used to insert the element at the end of list.
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.
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.
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.
The value of std::list
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With