Implementation principle of Vector in STD (implementation principle of Vector in standard template dynamic library)

Source: Internet
Author: User

The data structure we implement is to solve the dynamic open-up space usage during the running process (for example, we do not know how much we enter without stopping the input)

Two principles:

I. Stupid Methods

How much space is used and how much space is opened for the first time?

The second time we use space, we will open up space B larger than the first one, copy the data in A to B, then release a, and write new data in C.

Disadvantage: copying is too many times and the efficiency is low.


Ii. Improvement Measures

The vector has a parameter, which is used to fill in the reserved space. The size of the reserved space that we fill in is B. Here it is reserved and there is no real physical memory to be opened, if you need to open up space to do other things at this time, the opened space will avoid B. This will not make the data here become discontinuous.

Then open up the space to write data a, only a little bit of B, after the realloc in the vector submits data, the memory management mechanism of the operating system will map a "Memory Page" 4 K space for you to use. When B continues to open up space and fill in data d, at this time, the physical memory stored in D is not really open up, but is then used to open up the "Memory Page", only when 4 K space is used up, will be allocated a page for use again

When the data written exceeds B, A New Space C will be opened up, data in B will be copied to C, and B will be released

Advantage: the number of copies is greatly reduced and the efficiency is improved.



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.