Note 21.2.1.
Accessing elements by position like this is is often referred to as random access. It is not that we are accessing a random element, but rather that we can directly access any βrandomβelement we want by its position.
list allows for things that would be much more difficult or inefficient with a vector. However, they do have their own limitations. One key limitation is that none of these containers allow you to access elements directly by their position (index) in the collection. Given a std::list it is an error to say something like myList.at(3) to try to get the 4th element.
.at(i). Instead, we have to use an iterator to walk through all the elements in the container. (Or use a range based loop, which behind the scenes uses iterators.)
.begin() and an iterator to one past the end using .end(). We could then modify that iterator using expressions like myVec.begin() + 2 to get an iterator that points to the third element of the vector.
std::list called myList, we can get an iterator to the start of the list using myList.begin() and one past the end using myList.end(). However, not all iterator types provide the same capabilities.
++it) or backwards one element at a time using the predecrement operator (--it). This means that to get to the 3rd element in a list, we would need to start at myList.begin() and then do ++ two times to move forward to the 3rd element.
begin() still gives an iterator to the first element and end() to one past the last element. But an iterator can only move forward or backward one element at a time. Given where it is, there is no way to jump directly to the 4th element.list<string>, the iterator type would be
list<string>::iterator.
*it). This gives us access to the element the iterator is pointing at. We can either read that value or assign to the element.
*it looks just like the syntax for dereferencing a pointer in C++. The iterator is not a pointer, but it acts like one in many ways.