我一直在使用VS 2013社区学习C++入门.当我测试以下两个程序时.我很困惑因为我认为输出应该是同样的东西.为什么结果不同?第一个如下.
#include "stdafx.h"
#include<iostream>
#include<vector>
using std::vector;
using std::cout;
using std::cin;
using std::endl;
int main()
{
vector<int> ivec(10,0);
vector<int>::size_type cnt =ivec.size();
for (vector<int>::size_type ix = 0; ix != ivec.size(); ++ix)
{
--cnt;
ivec[ix] = cnt;
cout << ivec[ix] <<" "<<cnt<< endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
第二个程序如下.
#include "stdafx.h"
#include<iostream>
#include<vector>
using std::vector;
using std::cout;
using std::cin;
using std::endl;
int main()
{
vector<int> ivec(10,0);
vector<int>::size_type cnt =ivec.size();
for (vector<int>::size_type ix = 0; ix != ivec.size(); ++ix, --cnt)
{
ivec[ix] = cnt;
cout << ivec[ix] <<" "<<cnt<< endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
for像一个循环
for (a; b; c)
{
d;
}
Run Code Online (Sandbox Code Playgroud)
相当于以下内容
a;
while (b)
{
d;
c;
}
Run Code Online (Sandbox Code Playgroud)
因此,在循环体c完成后,部件中发生的事情就完成了.
在第二种情况下,--cnt表达发生后,你使用它,而在第一种情况下--cnt发生之前.