What is the point of declaring a vector length?

Feb 5, 2012 at 2:37am
When initializing vectors, why declare their length? Is there an advantage to this?

std::vector<int> numbers(10);

Why not just

std::vector<int> numbers;

After all, aren't vectors expandable versions of arrays?
Feb 5, 2012 at 2:53am
If you don't specify the size, the vector will be empty and you will have to fill it some other way e.g. using push_back, resize or insert.
Feb 5, 2012 at 2:56am
Thanks.

So std::vector<int> numbers(10); is not actually empty? What 10 integers are stored in the vector then?
Feb 5, 2012 at 3:09am
They will be 0 by default. You can choose another number by passing a second argument std::vector<int> numbers(10, 45); now all 10 integers will have value 45.
Last edited on Feb 5, 2012 at 3:09am
Feb 5, 2012 at 3:13am
Thank you! That is clear now.
Topic archived. No new replies allowed.