顺序容器的种类简单介绍
顺序容器类型 | 功能 | 头文件 |
---|---|---|
vector | 可变长度的数组,也叫向量 | < vector > |
deque | 双端队列,也就是可以两头插入和删除的队列。实际上也支持随机访问 | < deque > |
list | 一个双向链表 | < list > |
forward_list | 一个单项链表 | < forward_list > |
array | 固定大小的数组,和C语言当中的数组差不多 | < array > |
string | 常用的字符串 | < string > |
上面的除了array是固定大小不变的以外,剩下的容器都是可变长度,灵活增加和减少的。不同容易在不同的操作上面效率各有优劣,在内存当中的存储和管理方式也各有不同。其中array和froward_list是C++标准新增加的类型。
容器操作
内容比较多,截个图吧
迭代器
经常用于用来遍历和操作容器,迭代器的遍历范围是一个左闭右开的区间,比如有一个
vector<int> v={1,2,3,4}
auto beg=v.begin(),ed=v.end();
cout<<*beg<<endl;//输出1
cout<<*ed<<endl;//超出范围,但是编译器不会报错
现在又一对迭代器beg和ed分别指向同一个元素的begin()和end()那么
- 如果beg==ed,那么证明容器为空
- 如果beg!=ed,那么里面至少包含一个元素
- 可以对beg进行递增,使得beg==ed
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int> v={1,2,3,4};
auto ed=v.end();
for(auto beg=v.begin();beg!=ed;beg++)
cout<<*beg<<endl;
return 0;
}
如果想从后往前遍历和操作容器,可以使用反向迭代器。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int> v={1,2,3,4,5,6};
//rit的类型是vector<int>::reverse_iterator
for(auto rit=v.rbegin();rit!=v.rend();rit++)
cout<<*rit<<" ";
cout<<endl;
return 0;
}
如果只想遍历,不想对容器中的元素进行操作。可以是用const_iterator,那么反向的const迭代器就是
const_reverse_iterator
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int> v={1,2,3,4,5,6};
for(auto cit=v.cbegin();cit!=v.cend();cit++)
cout<<(*cit)<<" ";
cout<<endl;
for(auto rcit=v.crbegin();rcit!=v.crend();rcit++)
cout<<*rcit<<" ";
cout<<endl;
return 0;
}
书上说在C++11当中,begin和end成员有两种,一种const,另外一种是非const。根据调用的对象类型来返回是否为const
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int> v={1,2,3,4,5,6};
vector<int>::const_iterator cit=v.begin();//虽然是begin,但是实际上是cbegin
for(cit=v.begin();cit!=v.end();cit++)
++(*cit);
return 0;
}
to be continue~