Andres Lamberto
Andres Lamberto

Reputation: 106

help figuring out why this output is "01"

int main()
{
vector<int> v(5);
v[0]=0; v[1]=1; v[2]=2; v[3]=3; v[4]=4;

for (int i=0; i<v.size(); i++)
    v.pop_back();
for (int i=0; i<v.size(); i++)
    cout<<v[i];
cout<<"\n";

return 0;
}

i am confused as to why the output is "01". i would think the output is "0"

Upvotes: 0

Views: 72

Answers (3)

Saghir A. Khatri
Saghir A. Khatri

Reputation: 3128

as mentioned, second loop meets stopping condition at 3rd iteration, since i val is 3 and vector size is 2.

Upvotes: 0

Cameron
Cameron

Reputation: 98786

Trace each iteration of the first for-loop through:

i   v.size()    v (before pop_back)
0   5           0,1,2,3,4
1   4           0,1,2,3
2   3           0,1,2
3   2           0, 1

And the loop stops there (not popping when i == 3) since 3 < 2 is false. So the final contents of v after the loop is [ 0, 1 ].

Upvotes: 3

geofftnz
geofftnz

Reputation: 10092

If v.size() is evaluated each loop, then the loop limit is coming down as you pop items off your vector. It must pop the last 3 off before bailing out of the loop.

Upvotes: 3

Related Questions