what's wrong with vector

why output of this code gives the following output

0 0 0 0 0 1 2 3 4 5

Not sure what you’re trying to achieve here .

You declared the vector size as 5 and pushed 10 elements into it .

1 Like

I am learning STL, so I was just experiment with it. But what is reason behind that output.

Nothing is “Wrong” here, but as you say you’re experimenting with STL and didn’t understand the output I am telling it step by step.

vector < int > v(5);

Here you have declared a vector with 5 element all set to 0 (by default). You can change this default value of 0 to any other integer (because the vector is made of int) by using vector v (5,1) to set it to 1.
In other words you are using constructor #2 mentioned here


for(int i=0;i<10;i++){		
 	//v[i]=i+1;		
	v.push_back(i+1);
	}

Here you are pushing 10 values into the vector. NOTE that pushing does not alter any existing elements but adds new elements. So now your vector has the 5 earlier elements as well as these 10 more elements.


for(int i=0;i<10;i++){
		cout<< v[i] << " ";
	}

In this loop you are printing only the first 10 elements (not the whole vector). In order to print the whole vector either turn the loop till v.size() {more preferred} or till 15.

Hence your output justified.

@virresh

Thanks

//