Requests that the capacity of the allocated storage space for the elements of the vector container be at least enough to hold n elements.
This informs the vector of a planned change in size, which can be either to expand or shrink its storage capacity, although notice that the parameter n informs of a minimum, so the resulting capacity may be any capacity equal or larger than this.
When n supposes an expansion in capacity, a reallocation happens during the call to this function, granting that no further automatic reallocations will happen because of a call to vector::insert or vector::push_back until the vector size surpasses at least n (this preserves the validity of iterators on these calls).
A reallocation invalidates all previously obtained iterators, references and pointers.
In any case, a call to this function never affects the elements contained in the vector, nor the vector size (for that purposes, see vector::resize or vector::erase, which modify the vector size and content).
如:
例1:
vector<int> vecInt;
vecInt.reserve(20);
int n = vecInt.capacity();
int m = vecInt.size();
m的值为0
n的值为20
例2:
vector<int> vecInt;
vecInt.push_back(1);
int m = vecInt.size();
int n = vecInt.capacity();
m的值为1
n的值为1