Delete elements and clear memory holes in a vector.
Problem: The vector container in stl often creates the illusion of deletion, which is very annoying for c ++ programmers. The master of objective stl has listed it as 17th, use swap techniques to Trim excess capacity.
The term "memory holes" is provided by online scholars. I think it is very easy to remind myself of the trap of vector deletion to describe this basic phenomenon.
First, we will provide a piece of code:
35 void testvector ()
36 {
38 vector v;
39 v. push_back (1 );
40 v. push_back (2 );
41 cout <"v size =" <v. size () <"v capacity =" <v. capacity () <endl;
42 v. erase (v. begin ());
43 cout <"v size =" <v. size () <"v capacity =" <v. capacity () <endl;
44 vector (v). swap (v); // clear v and minimize its capacity
45 cout <"v size =" <v. size () <"v capacity =" <v. capacity () <endl;
47}
The result is as follows:
[Hfx @ didkey1 bin] $./test
V size = 2 v capacity = 2
V size = 1 v capacity = 2
V size = 1 v capacity = 1
Analysis:
We can clearly see this problem. At the first time v. erase (v. begin ();, the memory for deleting elements was not actually released, and its capacity was still there. I also briefly describe the problems in my life --
You took this 1000 litre of water for a trip to the desert. It started to be full. However, your journey made your water 1 litre, and it was on the road, if you don't have water resources to fill you up again, you will be dragging a 1000 litre
A large water tank carries 1 litre of water and you are not allowed to do so on your own. You only need to cut the water tank into 10 or 1 litre, smaller ......
The same is true for vector. If you drink water, you cannot narrow down the water tank --
-- Swap () swap function perfectly releases memory.
Vector (v). swap (v); // clear v and minimize its capacity
Note:
A. erase () function, which can only Delete content and cannot change the capacity;
Erase member function, which deletes the elements pointed to by the itVect iterator and returns the iterator after the itVect To be deleted. The iterator is equivalent to a smart pointer.
B. The clear () function can only empty the content and cannot change the capacity.
C. If the deletion of the vector container does not automatically release the memory, memory leakage occurs ??? No. The vector releases the memory during destructor.
D. If you want to release the memory while deleting the content, you can select the deque container.
E. About vector:
Vector is equivalent to an array in c ++. The array also needs to be given an array space size during initialization. When applying for a vector, a space will be reserved, such as 10, when the element exceeds 10, the vector Automatically splits the size
Expand to double, and copy the element to the past.
Example:
Vector (v). swap (v); clears the memory holes of v.
Vector (). swap (v); clear vec