Valid STL: use reserve to avoid unnecessary Memory Allocation

Source: Internet
Author: User

Use reserve to avoid unnecessary Memory Allocation
    • When you know exactly or approximately how many elements will eventually appear in the container
   vector   int  V;   // if you do not need to use reserve to allocate memory first, the following cycle will re-allocate the memory multiple times (involving expensive actions such as allocation, recycling, copying, and destructor)   v. reserve ( 1000 );  for  ( int  I =  1 ; I <=  1000 ; ++ I) {v. push_back (I) ;} 
    • Keep the maximum space you may need, and then, once you add full data, trim any excess capacity (you can considerUse swap to Trim excess capacityMethod)

InSize and capacityThe relationship between them allows us to predict when insertion will cause the vector or string to be re-allocated.

StringS ;...If(S. Size () <S. Capacity ()){// Push_back will not invalidate the iterator, pointer, or reference pointing to this string, because the size of the string must be greater than its size.S. push_back ('X');}

Valid STL: use reserve to avoid unnecessary Memory Allocation

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.