Research on vector length expansion mechanism of C + +

Source: Internet
Author: User

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 + +

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.