vector&list 效率比较
1、比较代码(https://blog.csdn.net/libaoshan55/article/details/77337878)
1 int main() { 2 cout << "Test vector and list time" << endl; 3 int N = 10000; 4 int count = 0; 5 while (count <= 3) { 6 vector<int> vecInt; 7 list<int> listInt; 8 clock_t start, finish; 9 cout << "N==" << N << endl; 10 start = clock(); 11 for (int i = 0; i < N; ++i) { 12 vecInt.push_back(i); 13 } 14 finish = clock(); 15 cout << "vector push_back 时间为" << (finish - start) << "毫秒" << endl; 16 //insert time 17 vector<int>::iterator pos_vec = vecInt.begin(); 18 ++pos_vec; 19 vecInt.insert(pos_vec, 99); 20 finish = clock(); 21 cout << "vector insert 时间为" << (finish - start) << "毫秒" << endl; 22 23 24 start = clock(); 25 for (int i = 0; i < N; ++i) { 26 listInt.push_back(i); 27 } 28 finish = clock(); 29 cout << "list push_back 时间为" << (finish - start) << "毫秒" << endl; 30 31 //insert time 32 start = clock(); 33 list<int>::iterator pos_ls = listInt.begin(); 34 ++pos_ls; 35 listInt.insert(pos_ls, 99); 36 finish = clock(); 37 cout << "list insert 时间为" << (finish - start) << "毫秒" << endl; 38 39 //vector<int>::iterator iter = vecInt.begin(); 40 //start = clock(); 41 //for (; iter!=vecInt.end(); ++iter) { 42 // *iter; 43 //} 44 //finish = clock(); 45 //cout << "vector'iterator 访问元素时间为 " << (finish - start) << "毫秒" << endl; 46 //start = clock(); 47 //for (int i = 0; i < vecInt.size(); ++i) { 48 // vecInt[i]; 49 //} 50 //finish = clock(); 51 //cout << "vector'[] 访问元素时间为 " << (finish - start) << "毫秒" << endl; 52 53 //start = clock(); 54 //for (list<int>::iterator iter = listInt.begin(); iter != listInt.end(); ++iter) { 55 // *iter; 56 //} 57 //finish = clock(); 58 //cout << "list 访问元素时间为 " << (finish - start) << "毫秒" << endl; 59 60 ++count; 61 N *= 10; 62 vecInt.clear(); 63 listInt.clear(); 64 cout << vecInt.capacity() << endl; 65 66 } 67 }
2、vector下标[ ]与迭代器iterator遍历效率比较结果:[ ]是iterator的十倍;
3、list与vector迭代器遍历效率比较:差不多
4、list与vector的push_back()效率比较:vector远超list
5、list与vector的insert()效率比较:vector效率远低于list,根本不是一个数量级