了解容器的好资源

Good sources to understand Containers

我正在研究容器及其不同的性能。
当 ,对于 vector,我读到类似

的内容

"inserting elements other than the back is slow"

但对于 list:

"fast insert/delete at any point"

我的问题是:

我正在搜索一些资源以更好地理解这些概念。

所有示例都将 link 编辑为 C++ 语言,因为我相信它在那里得到了完美的描述

向量

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time.

Vector是动态数组,但是可以管理分配给自己的内存。这意味着您可以创建长度在运行时设置的数组,而无需使用 new 和 delete 运算符(显式指定内存的分配和释放)。

列表

Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, the list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about a doubly linked list. For implementing a singly linked list, we use a forward list.

有两种类型的列表:

  • Double linked list 其中每个元素的地址为 [next][previous],要访问第一个或最后一个元素,您可以使用特定函数(例如,在列表中的 C++ front() 或 back() 中 - listName.front() 将 return 你是列表中的第一个 (0) 元素),head.previous 指向 NULLtail.next 指向 NULL;
  • Single linked list 其中每个元素只有 link(knows) 关于 [next] 元素,这个列表中的最后一个元素指向 至 NULL.

现在让我们回到你的问题:

how a vector is different from a list in such a way that the two sentences above are true? How is a vector built differently from a list? Is it because they store their elements in different memory parts? I was searching some sources to better understand these concepts.

正如我提到的,有 2 种类型的列表(单 linked 和双喜欢),当你要拥有它们时它们很好:

  • 许多 insertion/deletion 除了列表的结尾;

如果您打算:

,您可以使用矢量
  • 经常访问列表末尾的 insert/delete 个元素;
  • 访问随机位置的元素(因为您可以使用 [N] 访问任意位置的元素,其中 N 是元素的 index/position。

而在 List 中,您需要使用迭代器访问 position/index N 处的元素。

因此 vector 是一个动态数组,当您访问它时它们往往会执行得更快(因为它没有额外的包装器,并且您可以通过指针直接访问内存中的一个点)。

列表是一个序列容器(因此这个容器对一些基本语言功能进行了包装)通过为用户提供一些有用的方法来处理其元素而牺牲了一些点来支持插入和删除的额外简单性.

为了解决您的问题,我们可以得出以下结论:

向量

inserting elements other than the back is slow

列表

fast insert/delete at any point

这个可以通过结构来判断他们有什么。

  • Insertion List 中是 swift 因为它是一个 linked 列表,而这个 意味着什么?确切地说,这意味着要进行唯一的更改 实现它是改变 [previous ] 的指针和 [next] 项,我们完成了!
  • 而在 Vector 将花费 waaaay 更多的时间来插入元素而不是在末尾。 这可以用数组的概念来证明。如果您有一个包含一百万个元素的数组并且您想要 replace/delete/insert 数组最开头的元素,则需要更改更改元素之后的每个元素的位置。

列表与矢量图像:

图片取自以下来源: singly linked list double linked list double linked list 2nd image vector

此外,请尝试在此处 vector-vs-list-in-stl. Their comparison is well described there. + look through the-c-standard-template-library-stl 查看“容器”部分并检查描述及其方法。