vector&list 效率比较
转自:https://www.cnblogs.com/wllwqdeai/p/13441463.html
1、比较代码(https://blog.csdn.net/libaoshan55/article/details/77337878)
int main() {
cout << "Test vector and list time" << endl;
int N = 10000;
int count = 0;
while (count <= 3) {
vector<int> vecInt;
list<int> listInt;
clock_t start, finish;
cout << "N==" << N << endl;
start = clock();
for (int i = 0; i < N; ++i) {
vecInt.push_back(i);
}
finish = clock();
cout << "vector push_back 时间为" << (finish - start) << "毫秒" << endl;
//insert time
vector<int>::iterator pos_vec = vecInt.begin();
++pos_vec;
vecInt.insert(pos_vec, 99);
finish = clock();
cout << "vector insert 时间为" << (finish - start) << "毫秒" << endl;
start = clock();
for (int i = 0; i < N; ++i) {
listInt.push_back(i);
}
finish = clock();
cout << "list push_back 时间为" << (finish - start) << "毫秒" << endl;
//insert time
start = clock();
list<int>::iterator pos_ls = listInt.begin();
++pos_ls;
listInt.insert(pos_ls, 99);
finish = clock();
cout << "list insert 时间为" << (finish - start) << "毫秒" << endl;
//vector<int>::iterator iter = vecInt.begin();
//start = clock();
//for (; iter!=vecInt.end(); ++iter) {
// *iter;
//}
//finish = clock();
//cout << "vector'iterator 访问元素时间为 " << (finish - start) << "毫秒" << endl;
//start = clock();
//for (int i = 0; i < vecInt.size(); ++i) {
// vecInt[i];
//}
//finish = clock();
//cout << "vector'[] 访问元素时间为 " << (finish - start) << "毫秒" << endl;
//start = clock();
//for (list<int>::iterator iter = listInt.begin(); iter != listInt.end(); ++iter) {
// *iter;
//}
//finish = clock();
//cout << "list 访问元素时间为 " << (finish - start) << "毫秒" << endl;
++count;
N *= 10;
vecInt.clear();
listInt.clear();
cout << vecInt.capacity() << endl;
}
}
2、vector下标[ ]与迭代器iterator遍历效率比较结果:[ ]是iterator的十倍;
3、list与vector迭代器遍历效率比较:差不多
4、list与vector的push_back()效率比较:vector远超list
5、list与vector的insert()效率比较:vector效率远低于list,根本不是一个数量级
总结:
1、vector遍历能用[ ] 不用迭代器
2、插入操作多时使用list