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/