[英]Why doesn't this print anything on the screen?
#include <iostream>
using namespace std;
class A
{
public:
int index;
int t;
int d;
int sum;
};
A arr[1000];
bool comp (const A &a, const A &b)
{
if (a.sum < b.sum)
return true;
else if (a.sum == b.sum && a.index < b.index)
return true;
return false;
}
int main (void)
{
int n,foo,bar,i;
i = 0;
cin>>n;
while ( n != 0 )
{
cin>>foo>>bar;
arr[i].index = i+1;
arr[i].t = foo;
arr[i].d = bar;
arr[i].sum = arr[i].t+arr[i].d;
n--;
i++;
}
sort(arr,arr+n,comp);
for ( int j = 0; j < n; j++ )
cout<<arr[j].index;
cout<<"\n";
return 0;
}
因此,我制作了此程序,該程序接受來自用戶的值,然后根據特定條件對它們進行排序。 但是,當我嘗試打印數組的值時,它不會打印。 我不知道為什么 請幫忙。 謝謝!
PS:我什至嘗試不使用比較器功能就打印數組的值,但仍然無法打印。
編輯:得到了我的錯誤,正如一些驚人的人在評論中提到的那樣。 但是,將值輸入為
5
8 1
4 2
5 6
3 1
4 3
它應該以4 2 5 1 3
返回答案,但返回1 2 3 4 5
。 基本上,它根據每行中2個元素的總和進行排序並打印索引。 可能是什么問題?
它不是排序的,因為您正在修改while
循環中的n
值。
因此,當循環結束后n = 0
時,沒有排序(或稍后打印)的內容:
sort( arr, arr + n, comp);
相當於
sort( arr, arr + 0, comp);
最簡單的方法是使用for
循環:
for( int i=0; i<n; ++i )
{
....
}
這樣, n
保持不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.