Linear Containers特点
- 有
push_back()
、push_front()
、insert()
操作函数 - vector、deque可以使用下表访问数据
[]
- 无
find
函数,且存储无序 - 但可以使用
<algorithm>
库函数的find(begin(), end(), elem)
、sort(begin(), end())
来对数据进行查找和排序
一. vector容器
1. 特点
- 尾部插入:O(1)
- 头部和中部insert/remove 慢:O(n)
- 查找慢
2. 迭代器
使用方法如下:
vector<int> values{
1, 2, 3, 4, 5};
auto first = values.begin();
auto end = values.end();
while (first != end)
{
cout << *first << " ";
++first;
}
其中,关键字 auto
可以自动判断变量类型,相当于 vector<int>::iterator it
。
下面为迭代器各个位置的示意图:
注意:values 容器在增加容量之后,首个元素的存储地址发生了改变,此时再使用先前创建的迭代器,显然是错误的。因此,为了保险起见,每当 vector 容器的容量发生变化时,我们都要对之前创建的迭代器重新初始化一遍
3. 举例
vector容器的函数使用可以参考:vector
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// add element
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.insert(v.end(), 5);
v.pop_back();
v.insert(v.end(), {
5, 6});
cout << v.front() << endl; // 访问头部元素(可以修改值)
cout << v.back() << endl; // 访问尾部元素
v.pop_back(); // remove the last element
// insert
v.insert(v.begin(), 0);
// erase [v.begin()+2, v.begin()+4)
v.erase(v.begin()+2, v.begin()+4);
cout << v.size() << endl; // size
// v.clear();
if (v.empty()) // is empty
cout << "Empty" << endl;
vector<int> vec(v); // copy
v.swap(vec); // swap
cout << v[0] << endl;
// traverse fast
cout << endl;
for (auto it=v.begin(); it!=v.end(); it++){
cout << *it << " ";
}
cout << endl;
for (vector<int>::iterator it=v.begin(); it!=v.end(); it++){
cout << *it << " ";
}
cout << endl;
for (auto it: v){
cout << it << " ";
}
return 0;
}
输出结果如下:
1
6
5
0
0 1 4 5 6
0 1 4 5 6
0 1 4 5 6
二. deque容器
deque 是 double-ended queue 的缩写,又称双端队列容器。
1. 特点
- 头部/尾部插入:O(1)
- 中部insert/remove 慢:O(n)
- 查找慢
2. 使用
deque的使用 和vector类似,只是deque容器可以使用 push_back()
, pop_back()
, push_front()
和 pop_front()
来实现对头部和尾部的操作:
#include <iostream>
#include <deque>
using namespace std;
int main()
{
deque<int> deq = {
3, 4, 5, 6};
deq.push_front(2); // deq : {1, 2, 3, 4, 5, 6}
deq.push_front(1);
deq.push_back(7); // deq : {1, 2, 3, 4, 5, 6, 7, 8}
deq.push_back(8);
for (int i=0; i<deq.size(); i++){
cout << deq[i] << " ";
}
cout << "\n" << deq.at(0);
cout << "\n" << deq[0];
return 0;
}
结果为:
1 2 3 4 5 6 7 8
1
1
三. list 容器
1. 特点
- 任何位置插入:O(1)
- 查找慢 O(n)
- 无法用
[]
访问元素
2. 使用
#include <iostream>
#include <list>
#include <bits/stdc++.h>
using namespace std;
int main()
{
list<int> mylist = {
1, 2, 3, 4};
mylist.push_back(5);
mylist.push_front(0);
list<int>::iterator it = find(mylist.begin(), mylist.end(), 3);
mylist.insert(it, 10); // O(1)
mylist.erase(++it); // O(1)
cout << "Size: " << mylist.size() << "\n";
for (auto it=mylist.begin(); it!=mylist.end(); it++){
cout << *it << " ";
}
return 0;
}
参考内容:学习C++模板库(STL)、C++ STL教程