List 使用双向链表来管理元素。
一. List 与 vector或deque的区别
1.List 不支持随机存取。如果你要存取第5个元素,就必须从头开始数。
2.任何位置插入和删除都很快。
3.插入和删除不会造成其它元素pointers, references 和 iterators 失效。
4.List 的迭代器是双向迭代器,所以凡是用到随机存取的迭代器的算法(特别是排序算法)都不能用,只能用list 提供的特殊版本。
二. Remove() 函数
List 提供了 deque 所有的功能,还增加了 remove() 和 remove_if() 算法
//移除所有其值为 val 的元素
c.remove (val)
//移除所有op为true的元素
c.remove_if (op)
c.remove() 与 remove() 函数的区别:
#include <list>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
list<int> coll;
//6 5 4 3 2 1 1 2 3 4 5 6
for (int i=1; i<=6; ++i)
{
coll.push_front(i);
coll.push_back(i);
}
//打印
cout << "pre: ";
copy (coll.begin(), coll.end(), //source
ostream_iterator<int> (cout," ")); //destination
cout << endl;
//全局 remove 函数
//remove (coll.begin(), coll.end(), 3); //6 5 4 2 1 1 2 4 5 6 5 6
//list 版本的 remove 函数
coll.remove (3); //6 5 4 2 1 1 2 4 5
//打印
cout << "post: ";
copy (coll.begin(), coll.end(), //source
ostream_iterator<int> (cout," ")); //destination
cout << endl;
return 0;
}
注意:
全局的 remove() 函数并没有改变容量元素的数量,并且在操作上是后面的元素覆盖了前面的元素。
而 list.remove() 不会出现这种情况。
三. 变动性函数
//移除重复元素,只留下一个
c.unique()
c.unique(op)
//将 c2 所有元素转移到 c1 内,迭代器 pos 之前
c1.splice(pos, c2)
//将 c2 内 c2pos 所指元素转移到 c1 内,迭代器 pos 之前
c1.splice(pos, c2, c2pos)
//将 c2 内 [c2beg,c2end) 区间内的所有元素转移到 c1 内的迭代器 pos 之前
c1.splice(pos, c2, c2beg, c2end)
//按从小到大排序
c.sort()
//按op排序
c.sort(op)
//c1 和 c2 容器都是已序的,将 c2 的全部元素转移到 c1,并保证合并后的 list 仍为已序。
c1.merge(c2)
//c1 和 c2 容器都是已序好,将 c2 的全部元素转移到 c1,并保证合并后的 list 在op()原则下仍为已序
c1.merge(c2, op)
将所有元素反序
c.reverse()
注意:
1. 这些变动性算法,一个容器中元素增加,则另一个容器的元素必须减少。如spice 拼接操作,被拼接的c2容器内元素将不再存在。
2. merge() 操作,要求两个容器是已序的。
四. 实例代码
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
void printLists (const list<int>& list1, const list<int>& list2)
{
cout << "list1: ";
copy (list1.begin(), list1.end(), ostream_iterator<int>(cout," "));
cout << endl << "list2: ";
copy (list2.begin(), list2.end(), ostream_iterator<int>(cout," "));
cout << endl << endl;
}
int main()
{
//create two empty lists
list<int> list1, list2;
for (int i=0; i<6; ++i)
{
list1.push_back(i); //0 1 2 3 4 5
list2.push_front(i); //5 4 3 2 1 0
}
printLists(list1, list2);
//-find() 操作返回元素3的迭代器的位置
//把list1中的所有元素插入到list2中元素为3之前
list2.splice( find(list2.begin(),list2.end(), 3), list1 );
printLists(list1, list2);
//相当于倒置
list2.splice(list2.end(), list2, list2.begin());
printLists(list1, list2);
//排序,并去掉重复
list2.sort();
list1 = list2;
list2.unique();
printLists(list1, list2);
//合并
list1.merge(list2);
printLists(list1, list2);
return 0;
}