Search code examples
c++stdvectorallocationdoubly-linked-liststdlist

std::list implementation & pointer arithemetic.


As I understand it, std::vector allocates/de-allocates all the memory it requires each time it's elements grows or shrinks, therefore pointer arithmetic can be used to iterate the vector elements.

std::list on the other hand uses a double linked list, with each element pointing to the next and previous element.

Assuming(possibly wrongly) that std::list allocates it's memory dynamically, so memory is allocated, if and when required, incrementally. How is std::list still able to offer pointer arithmetic as a means to iterate it's elements?.


Solution

  • Roughly speaking, you can assume an std::list::iterator to be a container for pointer to a list element struct iterator { list::element *current };. And an element has pointers to the next and previous, like struct element { list::element *next, *previous }; When you increment that iterator, it just reassigns this pointer to point to the next element. Like it->current = it->current->next in linked lists. No pointer arithmetics involved.