Question about vector capacity and sizeof

Source: Internet
Author: User

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.

 

Related Article

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.