2.STL Sequence Containers

vector

初始化

1
2
3
4
5
6
7
8
vector<int> myVector(15);       //初始大小为15,其中值均为0
vector<string> myStringVector(10); //初始大小为10,其中均为空字符串

vector<double> myReals(20, 137.0); //初始大小为20,值均为137.0
vector<string> myStrings(5, "(none)"); //初始大小为5,值均为"(none)"

vector<double> myReals;
myReals(20, 137.0); // Error: Only legal to do this when the object is created

添加元素

1
2
push_back、insert
v.insert(v.begin() + n, e);

resize

resize可以在创建vector之后更改vector中的元素数量。

resize函数的语法与构造语法类似,可以指定多个元素,也可以指定多个元素和一个值,然后将调整vector的大小以容纳这么多元素。

但是,resize的行为与之前的构造有所不同,因为在使用resize时,vector可能已经包含元素。

resize的工作原理是从vector的末尾添加或删除元素,直到达到所需的大小。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
vector<int> myVector; // Defaults to empty vector
PrintVector(myVector); // Output: [nothing]

myVector.resize(10); // Grow the vector, setting new elements to 0
PrintVector(myVector); // Output: 0 0 0 0 0 0 0 0 0 0

myVector.resize(5); // Shrink the vector
PrintVector(myVector); // Output: 0 0 0 0 0

myVector.resize(7, 1); // Grow the vector, setting new elements to 1
PrintVector(myVector); // Output: 0 0 0 0 0 1 1

myVector.resize(1, 7); // The second parameter is effectively ignored.
PrintVector(myVector); // Output: 0

删除元素

pop_back:从vector序列中移除最后一个元素

erase:从vector中移除特定位置的元素。

1
2
3
myVector.erase(myVector.begin() + n); // n represents the index of the element to erase

myVector.clear(); //清除全部内容

Deque

vector只能高效的在一个方向上增长

如果deque比vector有更多的功能,为什么要使用vector?

主要原因是速度。这主要是因为两者实现方式的不同。

Container adaptors


2.STL Sequence Containers
https://ci-tz.github.io/2024/02/02/2-STL-Sequence-Containers/
作者
次天钊
发布于
2024年2月2日
许可协议