list序列容器
List序列容器提供了在容器的任何位置执行高效的插入和删除功能。
类模板list是用双链表实现的。也就是说,链表中每个节点都包含指向链表中前一个节点的一个指针和指向链表中后一个节点的指针。这就使得类模板list支持双向迭代器,允许以向前和向后的方式遍历容器。
下面以demo中的例子来说明list的用法。
- #include <iostream>
- using namespace std;
- #include <list>
- #include <algorithm>
- #include <iterator>
- template<typename T> void printList(const list<T> &listRef);
- int _tmain(int argc, _TCHAR* argv[])
- {
- const int SIZE = 4;
- int array[SIZE] = {2,6,4,8};
- std::list<int> values;
- std::list<int> otherValues;
- //push_front在values开始出插入元素,push_back在values的末尾处插入元素
- values.push_front(1);
- values.push_front(2);
- values.push_back(3);
- values.push_back(4);
- cout<<"元素值为:";
- printList(values);
- //sort成员函数按照升序排列list中的元素
- values.sort();
- cout<<"\n排序后包含的元素为:";
- printList(values);
- //在otherValues中插入元素
- otherValues.insert(otherValues.begin(),array,array+SIZE);
- cout<<"\n插入后,otherValues包含:";
- printList(otherValues);
- //删除otherValues中的元素,并插入到values中由第一个实参指定的迭代器前
- values.splice(values.end(),otherValues);
- cout<<"\nsplices 后,values包含:";
- printList(values);
- values.sort();
- cout<<"\n排序后,values包含的元素为:";
- printList(values);
- otherValues.insert(otherValues.begin(),array,array+SIZE);
- otherValues.sort();
- cout<<"\n插入并排序后,otherValues包含:";
- printList(otherValues);
- //移除otherValues元素并按照顺序插入到values中
- values.merge(otherValues);
- cout<<"\n合并后:\n values包含:";
- printList(values);
- cout<<"\n otherValues 包含:";
- printList(otherValues);
- values.pop_front();//删除list中的第一个元素
- values.pop_back();//删除list中的最后第一个元素
- cout<<"\npop_front和pop_back后:\n values包含:";
- printList(values);
- values.unique();//删除list中的所有重复元素,在执行这个操作前list必须是已经排好序的
- cout<<"\nunique后,values包含:";
- printList(values);
- //交换values和otherValues的元素
- values.swap(otherValues);
- cout<<"\nswap后:\n values包含:";
- printList(values);
- cout<<"\n otherValues包含:";
- printList(otherValues);
- //用otherValues中两个迭代器实参制定范围的内容替换values的内容
- values.assign(otherValues.begin(),otherValues.end());
- cout<<"\nassign后,values包含:";
- printList(values);
- values.merge(otherValues);
- cout<<"\nmerge后,values包含:";
- printList(values);
- values.remove(4);//从list中删除值4的所有副本
- cout<<"\nremove(4)后,values包含:";
- printList(values);
- cout<<endl;
- system("pause");
- return 0;
- }
- template<typename T> void printList(const list<T> &listRef)
- {
- if(listRef.empty())
- {
- cout<<"list is empty";
- }
- else
- {
- ostream_iterator<T> output(cout," ");
- copy(listRef.begin(),listRef.end(),output);
- }
- }
运行结果: