0
votes

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.

1
Unlike sizeof, vector::capacity returns the number of elements, not the number of bytes.Nathan Pierson
std::vector::capacity returns the number of elements the container has space for, not the number of allocated bytes.bnaecker
Where exactly did you quote this sentence from?einpoklum

1 Answers

4
votes

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]).