std :: list implementation&指针化学。 [英] std::list implementation & pointer arithemetic.

查看:255
本文介绍了std :: list implementation&指针化学。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,std :: vector分配/解除分配它需要的所有内存,每次它的元素增长或收缩,因此指针算术可以用于迭代矢量元素。

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另一方面使用双链表,每个元素指向下一个和上一个元素。

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

假设(可能是错误的)std :: list动态分配它的内存,所以内存被分配,如果需要的话,递增。如何std :: list仍然能够提供指针算术作为迭代它的元素的方法。

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

推荐答案

可以假设 std :: list :: iterator 是指向列表元素的指针的容器 struct iterator {list :: element * current}; 。一个元素有指向下一个和前一个的指针,如 struct element {list :: element * next,* previous}; 当你递增迭代器时,指向下一个元素。像链接列表中的 it-> current = it-> current-> next 。没有涉及指针算术。

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.

这篇关于std :: list implementation&指针化学。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆