序列式容器:
list是一个双向列表,它不是像vector那种连续线性空间,每次插入或者删除一个元素的时候,就配置或释放一个元素空间,因此list对空间不浪费。
list不仅是一个双向列表,还是一个环状双向列表,它执行插入操作时候,会插入到迭代器所在位置之前。
先看代码示例:
#include"Test.h" #include<vector> #include<list> #include<array> #include<algorithm>//为了使用find、sort等方法 void main() { setlocale(LC_ALL, "chs");//识别中文 //用list实现增改删除 list<int> v1; //初始化 v1.push_back(0); v1.push_back(2); v1.push_back(1); v1.push_front(3); for (list<int>::iterator v2 = v1.begin(); v2 != v1.end(); v2++) { cout << *v2 << endl; } list<int>::iterator v3 = find(v1.begin(), v1.end(), 2); if (*v3 == 2) { //增 v1.insert(v3, 8); } v3 = find(v1.begin(), v1.end(), 1); if (*v3 == 1) { //改 *v3 = 99; } for (list<int>::iterator v2 = v1.begin(); v2 != v1.end();) { //查 if (*v2 == 2) { //删 v2 = v1.erase(v2); } else { v2++; } } //sort(v1.begin(), v1.end()); int v5[4] = { 9,7,8,6 }; list<int> v7(v5, v5 + 4); v3 = find(v1.begin(), v1.end(), 8); v1.splice(v3, v7);//插入一个list列表 v1.reverse();//反转列表 v1.sort();//排序 for (list<int>::iterator v2 = v1.begin(); v2 != v1.end(); v2++) { cout << *v2 << endl; } getchar(); }
还有需要注意的一点是,不能调用全局的那个sort函数对list进行排序,需要用其内部的排序函数进行排序。
如果这样写:sort(v1.begin(), v1.end());
那么会发生编译报错:
我们需要使用其内部定义的函数进行排序操作:
v1.sort();
原因:
list不能使用STL的sort算法,必须使用自己的成员函数,因为STL的sort的函数只接受RamdonAccessIterator(随机访问迭代器,类似于vector的返回迭代器),其内部成员函数使用快速排序。
调试信息:
“It matters not what someone is born,but what they grow to be.”
参考资料:
《STL源码剖析》