基本概念
list类是一种双向链表。双向链表不是数组,不能使用下标,通常使用迭代器进行操作。
在list开头、末尾、中间插入元素:
- 开头:a.push_front()
- 末尾:a.push_back()
- 中间:insert(迭代器,数据),insert(迭代器,个数,数据),insert(迭代器,b.begin(), b.end()) //在某处插入b的所有数据
删除list中的元素:
- a.erase(迭代器) //删除某一元素
- a.erase(a.begin(), iter) //删除开始到iter的所有元素
对list中元素进行反转和排序
- a.reverse()
- a.sort()
示例代码
#include <iostream>
#include <list>
using namespace std;
void PrintListContents(const list<int>& listInput) //list显示函数
{
list<int>::const_iterator iter; //常迭代器
for(iter = listInput.begin(); iter != listInput.end(); ++iter)
cout << *iter << endl;
}
int main()
{
list<int> a; //a就是一个双向链表
a.push_front(4); //在前端添加数据
a.push_front(3);
a.push_front(2);
a.push_front(1);
a.push_back(5); //在后端添加数据
list<int> b;
b.push_back(100);
b.push_back(200);
b.push_back(300);
b.push_back(400);
b.push_back(500);
PrintListContents(b);
cout << endl;
list<int>::iterator iter1;
iter1 = a.begin();
++iter1;
a.insert(iter1, 10);
++iter1;
a.insert(iter1, 4, 20);
a.insert(a.begin(), ++b.begin(), --b.end());
PrintListContents(a);
//链表不是数组,不能使用下标
// list<int>::iterator iter;
// for(iter = a.begin(); iter != a.end(); ++iter)
// cout << *iter << endl;
//删除List中的元素
cout << endl;
list<int> x;
x.push_front(4);
x.push_front(3);
x.push_front(2);
list<int>::iterator iElementValueTwo;
// iElementValueTwo = x.insert(a.begin(), 2); //迭代器始终指向“2”这个数据,insert()会返回一个迭代器
iElementValueTwo = x.begin();
x.push_front(1);
x.push_front(0);
PrintListContents(x);
cout << endl;
x.erase(iElementValueTwo); //通过迭代器对数据2进行删除
PrintListContents(x);
cout << endl;
x.erase(iElementValueTwo, x.end());
PrintListContents(x);
cout << endl;
//反转和排序
list<int> y;
y.push_front(42);
y.push_front(99);
y.push_front(34);
y.push_front(56);
y.push_front(77);
PrintListContents(y);
cout << endl;
y.reverse(); //反转List
PrintListContents(y);
cout << endl;
y.sort(); //排序
PrintListContents(y);
cout << endl;
return 0;
}