Reputation: 401
According to c++ reference, vector's .capacity() function returns the "size of allocated storage capacity".
Doesn't this mean that a vector {1} should have capacity of sizeof(1) like an array? If so, then why does this code:
int main() {
vector<int> v = {1};
cout << v.capacity() << endl;
return 0;
}
produce 1 rather than 4(sizeof(v[0]))?
I just started learning c++, so forgive me if I sound foolish.
Upvotes: 0
Views: 299
Reputation: 3938
The capacity()
of a vector is better expressed as "the amount of space currently set aside that can be used for storage", expressed in terms of the number of potential elements that can be stored. Note that like size()
, this is the number of elements, not the number of bytes.
For example, a vector might have a size()
of 3 and a capacity()
of 4: this says that it is currently storing 3 elements, and has room for a maximum of 4 elements (total) before it will need to reallocate.
On the other hand, sizeof
returns the number of bytes required for an object of the given type, and is determined at compile time. For example, if you want the number of bytes currently allocated by the vector for storage, you could do vector.capacity() * sizeof(vector[0])
.
Upvotes: 4