std::list implementation & pointer arithemetic.

纵饮孤独 提交于 2019-12-12 04:56:30

问题


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?.


回答1:


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.



来源:https://stackoverflow.com/questions/28463343/stdlist-implementation-pointer-arithemetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!