我正在尝试进行冒泡排序。这就是我所拥有的:
#include <iostream>
#include <vector>
using namespace std;
int main() {
double small;
double big;
double i;
vector<double>list;
while(cin){
cin>>i;
list.push_back(i);
}
for(i=0;i<list.size()-1;i++){
small=list[i];
big=list[i+1];
if(small<=big){
}
else{
list[i]=big;
list[i+1]=small;
}
}
for(i=0;i<list.size()-1;i++)
cout<<list[i]<<'\n';
return 0;
}
这是我的意见:
123
4141
515
231366
21378
12990
5
6
8
9
但它输出了这个:
123
515
4141
21378
12990
5
6
8
9
9
231366
预期输出应该是:5,6,8,9,123,515,4141,12990,21378,231366。(忽略这一点,我是愚蠢的,输出是正确的,除了重复的数字)。有帮助吗?对不起,如果这是微不足道的。
答案 0 :(得分:0)
while(cin)
,因此9被读取两次,它应该是
while(cin >> i){
list.push_back(i);
}
答案 1 :(得分:0)
你得到一个额外的9
,因为这是你输入的最后一件事,你没有正确地摆脱循环。因此,您最终会将其添加到列表中两次。这样的事情更合适:
while(cin>>i){
list.push_back(i);
cout << "Adding " << i << "\n";
}
在您之前的原因中,您有以下内容:
while(cin){
cin>>i; // <-- reaches the end of file
list.push_back(i); // <-- puts something in the list even though we didn't read anything
}
请注意,当cin
到达EOF
时,您仍会将i
添加到列表中,该列表的旧值仍为cin
,但未读取除EOF
之外的任何输入。我在第一个代码段中的正确解决了这个问题。
答案 2 :(得分:0)
您的输入循环运行了太多次,在列表末尾给出了重复元素。如果将while循环更改为:
while(cin >> i){
list.push_back(i);
}
然后最后一个元素只添加一次。您还需要更改输出循环的边界。
关于while (cin)
答案 3 :(得分:0)
您必须运行嵌套循环
"SHA2" - HEAD
Jun 26
some comment -1
"SHA1" - Origin
Jun 25
some comment -2
现在你将231366(最大的数字)移到列表末尾。你必须迭代。