Resize () and reserve () differences in stl--vectors

Source: Internet
Author: User
  • Recently wrote a small stl--tinystl. There are some basic things that need to be recorded, so I'm going to write something more convenient for later viewing.
  • Let's look at the two usages of the resize () function in C + + Primer:

    1, resize (n)

    Adjusts the length of the container so that it can hold n elements.

    If n is less than the current size of the container, the extra element is removed.

    Otherwise, the element with the value initialization is added.

    2, resize (n,t)

    One more parameter T, which initializes all newly added elements to T.

    And the use of Reserver () has only one

    Reserve (N)

    Pre-allocates storage space for n elements.

    To understand the difference between these two functions, it is first to clarify the difference between the capacity (capacity) of the container and the size (length).

    Size refers to the number of elements currently owned by the container;

    Capacity, however, refers to the total number of elements that a container can store before it must allocate new storage space.

    It can also be said to be the size of the pre-allocated storage space.

    The resize () function is closely related to the size of the container. When resize (n) is called, the container's size is n.

    Whether the capacity is affected depends on whether the resized container's size is greater than capacity.

    The reserve () function is closely related to the capacity of the container.

    After calling reserve (N), if the container's capacity<n, the memory space is redistributed, so that capacity equals N.

    What if capacity>=n? Capacity no change.

    From the use of the two functions can be found that the container calls the resize () function, all the space has been initialized, so it can be directly accessed.

    The reserve () function pre-allocates space is not initialized, so it is inaccessible.

Resize () and reserve () differences in stl--vectors

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.