C ++ primer provides a detailed description of the auto-Growth Problem of the vector container, particularly the two member functions capacity and reserve. For exampleProgramInstructions:
Vector1
# Include < Iostream >
# Include < Vector >
Using Namespace STD;
Int Main ()
{
Vector < Int > VEC;
Print (VEC );
For (Vector < Int > : Size_type IX = 0 ; Ix ! = 24 ; Ix ++ )
{
VEC. push_back (IX );
}
Cout < " Size: " < VEC. Size () < " , Capacity: " < VEC. Capacity () < Endl;
VEC. Reserve ( 50 );
While (VEC. Size () ! = VEC. Capacity ())
{
VEC. push_back ( 0 );
}
Cout < " Size: " < VEC. Size () < " , Capacity: " < VEC. Capacity () < Endl;
VEC. push_back ( 0 );
Cout < " Size: " < VEC. Size () < " , Capacity: " < VEC. Capacity () < Endl;
Return 0;
}
The running result is as follows:
I just put cout <"Size:" <Vec. size () <", capacity:" <Vec. capacity () <Endl; this sentence is replaced with the function:
Void print (vector <int> VEC)
{
Cout <"Size:" <Vec. Size () <", capacity:" <Vec. Capacity () <Endl;
}
The main function is changed to the following:
Vector2
Int Main ()
{
Vector < Int > VEC;
Print (VEC );
For (Vector < Int > : Size_type IX = 0 ; Ix ! = 24 ; Ix ++ )
{
VEC. push_back (IX );
}
// Cout <"Size:" <Vec. Size () <", capacity:" <Vec. Capacity () <Endl;
Print (VEC );
VEC. Reserve ( 50 );
While (VEC. Size () ! = VEC. Capacity ())
{
VEC. push_back ( 0 );
}
// Cout <"Size:" <Vec. Size () <", capacity:" <Vec. Capacity () <Endl;
Print (VEC );
VEC. push_back ( 0 );
// Cout <"Size:" <Vec. Size () <", capacity:" <Vec. Capacity () <Endl;
Print (VEC );
Return 0 ;
}
The results are no longer the same. Result:
I don't understand why.
There is another problem. Is the sizeof problem of vector. At the end of the program, I added the following sentence:
Cout <"size of VEC:" <sizeof (VEC) <Endl;
The result is 16 in vc6.0, 20 in vs2008, and 12 in G ++.
They are all tested on the same machine. Please take a look at the reason.