From Source:
C + + Primer Fifth Edition, Exercise 9.38Write A program to explorer how vectors growin the library for you.
Environment:
WIN 7 + VS 32bit
Test code:
#include <iostream> #include <fstream> #include <vector>using namespace Std;int main () {Vector<int > Vec;vector<int>::size_type tmp = 0;ofstream ofs ("Matrix.txt"); for (int i = 0, j = 1; i < 10000000; i++) {Vec. Push_back (i); if (vec.capacity ()! = tmp) {cout << J << "" << vec.capacity () << Endl;ofs << J << "" << vec.capacity () << endl;tmp = Vec.capacity (); j + +;}} return exit_success;}
Operation Result:
1 12 23 34 45 66 97 138 199 2810 4211 6312 9413 14114 21115 31616 47417 71118 106619 159920 239821 359722 539523 809224 12 13825 1820726 2731027 4096528 6144729 9217030 13825531 20738232 31107333 46660934 69991335 104986936 157480337 236220438 3 54330639 531495940 797243841 11958657
visualization of matlab:
Mat = Load (' matrix.txt '), figure (1) Plot (Mat (:, 1), Mat (:, 2)), Hold On;plot (Mat (:, 1), Mat (:, 2), ' r* '), figure (2) plot (Mat ( :, 1), Log (Mat (:, 2))), Hold On;plot (Mat (:, 1), Log (Mat (:, 2)), ' r* ');
Normal Coordinates:
Logarithmic coordinates:
Conclusion:
Vector growth increases exponentially in the system, so time and space are more balanced.
More specifically, you can refer to http://blog.csdn.net/dodolzg/article/details/6333779
Accident:
If we put the code in the
Vec.push_back (i);
Change to
Vec.resize (i)//result same
Vec.reserve (i)//results each cycle capacity change, and equals I
Note In actual use, if the size of the vector is very determined, you can use reserve directly, save space, will not be "forced" to allocate extra memory. Other cases are more efficient with resize.
Finish
Research on vector length expansion mechanism of C + +