Feb 5, 2012 at 2:37am UTC
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 UTC
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 UTC
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 UTC
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 UTC
Feb 5, 2012 at 3:13am UTC
Thank you! That is clear now.