关于for循环中 != 和 < 的问题
做c++ primer上面题时,我自己写的for循环终止条件用的 != ,结果输出结果后,还出现一大串乱码(在输入很少几个数时,不会出现这种情况),还显示要终止程序。答案上for循环终止条件用的 < ,我将其改为!=后,在出现正确结果后,也出现一大串乱码,然后显示要终止程序。
有问题的for循环已在代码中注释出来
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
//读入数据到 vector 对象
cout << "Enter numbers(Ctrl+Z to end):" << endl;
while (cin>>ival)
ivec.push_back(ival);
//计算相邻元素的和并输出
if (ivec.size() == 0)
{
cout << "No element?!" << endl;
return -1;
}
cout << "Sum of each pair of adjacent elementsin the vector:"
<< endl;
vector<int>::size_type cnt = 0;
for (vector<int>::iterator iter = ivec.begin();
iter < ivec.end()-1; //此处 < 换成 != 后就出问题
iter = iter + 2)
{
cout << *iter + *(iter+1) << "\t";
++cnt;
if ( cnt % 6== 0) //每行输出 6 个和
cout << endl;
}
if (ivec.size() % 2 != 0) //提示最后一个元素没有求和
cout << endl
<< "The last element is not been summed "
<< "and its value is "
<< *(ivec.end()-1) << endl;
return 0;
}
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
//读入数据到 vector 对象
cout << "Enter numbers(Ctrl+Z to end):" << endl;
while (cin>>ival)
ivec.push_back(ival);
//计算相邻元素的和并输出
if (ivec.size() == 0)
{
cout << "No element?!" << endl;
return -1;
}
cout << "Sum of each pair of adjacent elementsin the vector:"
<< endl;
vector<int>::size_type cnt = 0;
for (vector<int>::iterator iter = ivec.begin();
iter < ivec.end()-1; //此处 < 换成 != 后就出问题
iter = iter + 2)
{
cout << *iter + *(iter+1) << "\t";
++cnt;
if ( cnt % 6== 0) //每行输出 6 个和
cout << endl;
}
if (ivec.size() % 2 != 0) //提示最后一个元素没有求和
cout << endl
<< "The last element is not been summed "
<< "and its value is "
<< *(ivec.end()-1) << endl;
return 0;
}
我输入的是1 32 456 67 88790 2345 67 234 67989 32 4 47
请各位解答下,谢谢!!