开发者

help figuring out why this output is "01"

开发者 https://www.devze.com 2023-02-17 13:35 出处:网络
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++)
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 ou开发者_如何转开发tput is "01". i would think the output is "0"


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 ].


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消