vector 和 list的区别
vector | list | |
---|---|---|
定义 | 动态数组 | 双向链表 |
增加 | push_back | push_back, push_front, insert |
删除 | pop_back | pop_back, pop_front, remove |
排序 | 头文件 sort | 成员函数 sort |
list经过排序、插入操作后,迭代器不会失效,仍指向原来的元素
#include<iostream>
#include<list>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
void print(const T& continer){
for(auto i = continer.begin(); i != continer.end(); ++i){
cout << *i << " ";
}
cout << endl;
}
int main(){
list<int> a {9, 8, 0, 7};
cout << "origin: ";
print(a);
cout << "after insert: ";
auto it = a.begin();
a.push_front(10);
print(a);
cout << "iterator it: " << *it << endl;
a.sort();
cout << "after sort: ";
print(a);
cout << "iterator it: " << *it << endl;
return 0;
}
output
origin: 9 8 0 7
after insert: 10 9 8 0 7
iterator it: 9
after sort: 0 7 8 9 10
iterator it: 9
而vector不满足这样的情况
#include<iostream>
#include<list>
#include<vector>
#include<algorithm>
using namespace std;
template<typename T>
void print(const T& continer){
for(auto i = continer.begin(); i != continer.end(); ++i){
cout << *i << " ";
}
cout << endl;
}
int main(){
vector<int> a {9, 8, 0, 7};
cout << "origin: ";
print(a);
cout << "after insert: ";
auto it = a.begin();
a.insert(a.begin() ,10);
print(a);
cout << "iterator it: " << *it << endl;
sort(a.begin(), a.end());
cout << "after sort: ";
print(a);
cout << "iterator it: " << *it << endl;
return 0;
}
output
origin: 9 8 0 7
after insert: 10 9 8 0 7
iterator it: 0
after sort: 0 7 8 9 10
iterator it: 0