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,根本不是一個數量級