list容器
介绍
list容器与双向链表
用途
快速插入删除
头文件以及构造方法
#include <list>
using namespace std;
int main(){
list<int> l;
插入数据以及遍历
int main(){
list<int> l;
for (int i = 0; i < 3; i ++ ) l.push_back(i + 1);
list<int>::iterator iter;
for (iter = l.begin(); iter != l.end(); iter ++)
cout << *iter << ' ';
return 0;
}
list函数
插入
从末端插入元素[push_back()]
从头部插入元素[push_front()]
l.push_back(1);
l.push_back(2);
l.push_front(3);
l.push_front(4);
list<int>::iterator iter;
for (iter = l.begin(); iter != l.end(); iter ++)
cout << *iter << ' ';
//4 3 1 2
获取头部元素[front()]与尾部元素[back()]
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_front(3);
l.push_front(4);
//4 3 1 2
cout << l.front() << endl;//4
cout << l.back() << endl;//2
删除最后一个元素[pop_back()]与删除第一个元素[pop_front()]
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_front(3);
l.push_front(4);
//4 3 1 2
l.pop_back();//4 3 1
//l.pop_front();//4 3 1
判断是否为空[empty()]
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_front(3);
l.push_front(4);
if (l.empty()) puts("Yes");
else puts("No");
清空list内的所有元素[clear()]
插入一个元素或多个元素[insert()]
删除一个元素或一个区间[erase()]
补充
插入下标为x的后面
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_front(3);
l.push_front(4);
//4 3 1 2
//插入下标为2的后面
int i = 0;
list<int>::iterator it = l.begin();
while (it != l.end() && i <= 2){
++ it;
++ i;
}
//4 3 1 7 2
l.insert(it, 7);