Vector memory release Problems

Source: Internet
Author: User

The container processing is only used for use and is not easy to understand. However, a problem occurred while running the program today. The released space is not actually released. So I found some articles on the Internet to solve the problem.

Solution: use swap and clear to release space together.

Principle: create a temporary copy that is consistent with the original vector. It is worth noting that the copy at this time (the system allocates the capacity when applying for space) the capacity is as small as possible to meet the required data. The copy is then exchanged with the original vector. Now, after the SWAp is executed, the temporary variables will be destroyed and the memory will be released. At this time, V is the original temporary copy, and the temporary copy after switching is the vector with a very large capacity (but it has been destroyed ).

Usage: Example:

1 # include <iostream> 2 # include <vector> 3 4 using namespace STD; 5 6 vector <string> V; 7 char ch; 8 9 int main () 10 {11 12 for (INT I = 0; I <1000000; I ++) 13 v. push_back ("abcdefghijklmn"); 14 CIN> CH; 15 // check whether the memory usage is 54m16 17 v. clear (); 18 CIN> CH; 19 // check again at this time, still occupying 54m20 21 cout <"vector capacity is" <v. capacity () <Endl; 22 // The capacity is 104857623 24 vector <string> (V ). swap (V); 25 26 cout <"vector capacity:" <v. capacity () <Endl; 27 // The capacity is 028 CIN> CH; 29 // check the memory. If 10 m + is released, the data memory is 30 return 0; 31}
View code

Reference: http://blog.jobbole.com/37700/

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.