Vector syntax: resize and reserve

Hi All,
We can construct vector in following ways
1
2
3
vector<int>v1;          //create an empty vector
vector<int>v2(arr,arr+4);  ///to create vector from an array
vector<int<v3(v2);          //throuh copy constructor 


But I have come across some program in a forum,they have create vector like this

vector<int>v(10,5)

I am clueless ,is this allowed?,what syntax allows this?

if a vector is create like this
1
2
3
4
5
vector<int>v(3);
v.push_back(1);
v.push_back(2);
v.push_back(3)
v.resize(2);

Now I am cusrious to know what are the changes those will happen in vector v because of resizing it?

Thanks in advance
vector<int>v(10,5)

I am clueless ,is this allowed?,what syntax allows this?

Yes, it's the "fill constructor". The vector will contain ten int's of value 5.
http://www.cplusplus.com/reference/vector/vector/vector/

Now I am cusrious to know what are the changes those will happen in vector v because of resizing it?


http://www.cplusplus.com/reference/vector/vector/resize/

Resizes the container so that it contains n elements.

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).


In your example, the vector will contain {0, 0}.

1
2
3
4
5
vector<int>v(3); // {0, 0, 0}
v.push_back(1);  // {0, 0, 0, 1}
v.push_back(2);  // {0, 0, 0, 1, 2}
v.push_back(3)   // {0, 0, 0, 1, 2, 3}
v.resize(2);     // {0, 0} 

Last edited on
Topic archived. No new replies allowed.