顺序容器内的元素按其位置存储和访问。除顺序容器外,标准库还定义了几种关联容器,其元素按键(key)排序
容器类共享公共的接口,这使标准库更容易学习,只要学会其中一种类型就能运用另一种类型。每种容器类型提供一组不同的时间和功能折衷方案。通常不需要修改代码,只需改变类型声明,用一种容器类型替代另一种容器类型,就可以优化程序的性能。
标准库定义了三种顺序容器类型:vector、list、deque(双端队列double-ended queue)
容器适配器,可以将新定义的操作接口来适配,原始的容器类型所提供的操作。stack、queue、priority_queue
Sequential Containers 顺序容器 | |
---|
vector | Supports fast random access 支持快速随机访问 #include <vector> | list | Supports fast insertion/deletion 支持快速插入/删除 #include <list> | deque | Double-ended queue 双端队列 #include <deque> | Sequential Container Adaptors 顺序容器适配器 | stack | Last in/First out stack 后进先出(LIFO)堆栈 | queue | First in/First out queue 先进先出(FIFO)队列 | priority_queue | Priority-managed queue 有优先级管理的队列 |
|
9.1 顺序容器的定义
所有的容器都是类模板,都定义了默认构造函数,用于创建指定类型的空容器对象。默认构造函数不带参数。(可以免去初始化)
C<T> c; | Create an empty container named c. C is a container name, such as vector, and T is the element type, such as int or string. Valid for all containers. 创建一个名为 c 的空容器。C 是容器类型名,如 vector,T 是元素类型,如 int 或 string 适用于所有容器。 | C c(c2); | Create c as a copy of container c2; c and c2 must be the same container type and hold values of the same type. Valid for all containers. 创建容器 c2 的副本 c;c 和 c2 必须具有相同的容器类型,并存放相同类型的元素。适用于所有容器。 | C c(b, e); | Create c with a copy of the elements from the range denoted by iterators b and e. Valid for all containers. 创建 c,其元素是迭代器 b 和 e 标示的范围内元素的副本。适用于所有容器。 | C c(n, t); | Create c with n elements, each with value t, which must be a value of the element type of C or a type convertible to that type. 用 n 个值为 t 的元素创建容器 c,其中值 t 必须是容器类型 C 的元素类型的值,或者是可转换为该类型的值。 Sequential containers only. 只适用于顺序容器 | C c(n); | Create c with n value-initialized (Section 3.3.1, p. 92) elements. 创建有 n 个值初始化(第 3.3.1 节)(value-initialized)元素的容器 c。 Sequential containers only. 只适用于顺序容器 |
|