C ++: resize () function in vector VS reserve () function

Source: Internet
Author: User

Http://www.cplusplus.com/reference/vector/vector/vector/

When the two functions are accidentally used during code writing, the program runs and crashes, and the two functions are different.

Void reserve (size_type n );

The reserver function is used to give the vectorPre-allocationThe size of the storage area, that is, the value of capacity, but the memory is not initialized. The reserve parameter n is the size of the pre-allocated memory recommended. The actual allocation may be equal to or greater than this value, that is, the value of n is greater than capacity, the reallocate memory capacity value is greater than or equal to n. In this way, when ector calls the push_back function to make the size exceed the original default capacity value, the overhead of memory redistribution is avoided.

Note that the memory space allocated by the reserve function only indicates that the vector can use the memory, but the vector cannot effectively access the memory space, during access, the program crashes.

Void resize (size_type n );
Void resize (size_type n, value_type val );

Resize FunctionReallocationTo change the container size and create an object.

When n is less than the current size () value, the vector first reduces the size () value to save the first n elements, and then deletes the elements that exceed n (remove and destroy)

When n is greater than the current size () value, the vector inserts a corresponding number of elements so that the size () value reaches n and initializes these elements, if the second resize function is called and val is specified, the vector uses val to initialize these newly inserted elements.

When n is greater than the capacity () value, the memory storage space is automatically allocated.

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.