顺序容器之list

来源:互联网 发布:电子阅读器软件 编辑:程序博客网 时间:2024/06/01 10:13

1、list

---- list表示双向链表。除了第一个和最后一个元素外,每个元素都与前后的元素相连接,这意味着可以双向遍历list。

---- list和vector之间的区别和联系:

--1)list中任一位置进行插入和删除的时间都是固定的;

vector在结尾处有固定的插入和删除时间,结尾处之外插入和删除的时间是线性的。

--2)vector强调的是进行快速随机访问,而list强调的是元素的快速插入和删除。

--3)list和vector都是可反转容器。但是list不支持数组表示法和随机访问。

与矢量迭代器不同,向容器中插入或删除元素之后,链表迭代器指向元素将不变。

例如:假设不扩展vector容量的情况下,有一个指向第5个元素的迭代器,在起始处插入一个元素,此时,必须移动其他所有元素,

以便腾出位置,因此插入后,第5个元素包含的值将是以前第四个元素的值,迭代器指向的位置不变,但数据不同。在list中插入新

元素并不会移动已有的元素,而只是修改链接信息。指向某个元素的迭代器仍然指向该元素,但它链接的元素可能与以前不同。

void merge(list &X)将链表x与调用链表合并。两个链表必须是已经排好序的。
合并后的、经过排序的链表保存在调用链表中,x为空。
复杂度为线性时间
void remove(const T &val)从链表中删除val的所有实例(值等于value的所有元素)
复杂度为线性时间
void sort()对链表按从小到大进行排序:N个元素的复杂度为NlogNvoid splice(iterator,list<T> x)将链表x的内容插入到指定的迭代器前面,x将为空。
复杂度为固定时间(拼接)
void unique()将连续的相同元素压缩为单个元素。复杂度为线性时间

#include <iostream>#include <vector>#include <list>#include <string>using namespace std;int main(){list<int> one(5,42); //10 ints:each has value 42int num[5]={1,2,4,8,6};list<int> two;two.insert(two.begin(),num,num+5);int more[6] = {7,4,6,5,3,9};list<int> three(two);three.insert(three.end(),more,more+6);list<int>::iterator itor;cout<<"List one:"<<endl;for(itor=one.begin();itor!=one.end();++itor){cout<<*itor<<" ";}cout<<endl<<"-----------------------\nList two: "<<endl;for(itor=two.begin();itor!=two.end();++itor){cout<<*itor<<" ";}cout<<endl<<"-----------------------\nList three:"<<endl;for(itor=three.begin();itor!=three.end();++itor){cout<<*itor<<" ";}three.remove(6);//remove the elements which value equals to 6cout<<endl<<"-----------------------\nList three after remove 6:"<<endl;for(itor=three.begin();itor!=three.end();++itor){cout<<*itor<<" ";}three.sort();cout<<endl<<"-----------------------\nList three after sort():"<<endl;for(itor=three.begin();itor!=three.end();++itor){cout<<*itor<<" ";}three.merge(one);cout<<endl<<"-----------------------\nList three after merge(one):"<<endl;for(itor=three.begin();itor!=three.end();++itor){cout<<*itor<<" ";}three.unique();cout<<endl<<"-----------------------\nList three after unique():"<<endl;for(itor=three.begin();itor!=three.end();++itor){cout<<*itor<<" ";}three.splice(three.end(),two);cout<<endl<<"-----------------------\nList three after splice two:"<<endl;for(itor=three.begin();itor!=three.end();++itor){cout<<*itor<<" ";}cout<<endl;system("pause");return 0;}
输出:



0 0
原创粉丝点击