#include <iostream>#include<vector>#include<stdint.h>#include<ctime>intMain () {Constuint32_t loop =1000000; Std::vector<int32_t>VEC; clock_t Timestart=0; for(Uint32_t i =0; I < loop; ++i) {vec.push_back (i); } //Test Time Use//1.by IndexTimestart =clock (); for(Uint32_t i =0; I < vec.size (); ++i) {vec[i]; } std::cout<< clock ()-Timestart <<"Ms"<<Std::endl; //2.by iteratorTimestart =clock (); for(Std::vector<int32_t>::const_iterator it = Vec.begin (); It! = Vec.end (); + +it) { *it; } std::cout<< clock ()-Timestart <<"Ms"<<Std::endl; //3.by Auto IteratorTimestart =clock (); for(Auto it = Vec.begin (); It! = Vec.end (); + +it) { *it; } std::cout<< clock ()-Timestart <<"Ms"<<Std::endl; GetChar (); return 0;}
The code is simple, build a vector containing several integers, traversing in three ways, counting the time spent, the results are as follows:
It can be found that, according to the traditional subscript way of the efficiency of the fast is not stint, although this method is prone to write the wrong subscript and caused the cross-border situation, but when the code is effective, it is a point that can not be ignored.
Comparison of efficiency of three kinds of traversal methods for C + + std::vector