The resize function changes the size member, and size represents the actual number of elements in the current container.
The reserve function changes the size of the capacity member, and the capacity member represents the number of containers that the container can store in total.
For example, to filter some elements of vector A to the vector B (assuming B is the newly defined vector), you can use the COPY_IF function at this time.
But the vector b space is not enough, what to do.
The reserve function should be used to change its capacity at this time.
Why not resize. In fact, resize can achieve the same effect. But the side effect of resize is to invoke the default constructor of the element type to actually construct the object to fill the vector.
Take a look at a test code:
void Testreserve ()
{
cout << "Test Reserve" << Endl;
Vector<mclass> VEC;
Vec.reserve (5);
}
void Testresize ()
{
cout << "Test Resize" << Endl;
Vector<mclass> VEC;
Vec.resize (5);
}
int main ()
{
Testreserve ();
Testresize ();
return 0;
}
Program execution Results:
PS: (1) also works for string.
(2) The reserve member only changes the capacity of the container, but does not mean that there are actual elements stored inside. Note When you use the subscript method to access.