简体   繁体   English

为什么这样在屏幕上不打印任何内容?

[英]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;
}

So, I made this program which accepts values from users, and then sorts them on the basis of a specific condition. 因此,我制作了此程序,该程序接受来自用户的值,然后根据特定条件对它们进行排序。 However, when I try to print the values of the array, it doesn't print it. 但是,当我尝试打印数组的值时,它不会打印。 I don't know why. 我不知道为什么 Please help. 请帮忙。 Thanks! 谢谢!

PS: I even tried to print the value of the array without use of comparator function, but still it doesn't print. PS:我什至尝试不使用比较器功能就打印数组的值,但仍然无法打印。

Edit: Got my error, as mentioned by some amazing people in the comments. 编辑:得到了我的错误,正如一些惊人的人在评论中提到的那样。 However, on inputting the values as, 但是,将值输入为

5
8 1
4 2
5 6
3 1
4 3

It should return the answer as 4 2 5 1 3 but instead it returns 1 2 3 4 5 . 它应该以4 2 5 1 3返回答案,但返回1 2 3 4 5 Basically, it sorts according to the sum of the 2 elements in each row and prints the index. 基本上,它根据每行中2个元素的总和进行排序并打印索引。 What might be the problem? 可能是什么问题?

It is not sorting because you are modifying the value of n in the while loop. 它不是排序的,因为您正在修改while循环中的n值。

So, when n = 0 after the loop ends, there is nothing to sort (or to print later for that matter): 因此,当循环结束后n = 0时,没有排序(或稍后打印)的内容:

sort( arr, arr + n, comp);

is equivalent to 相当于

sort( arr, arr + 0, comp);

Easiest approach would be to use a for loop: 最简单的方法是使用for循环:

for( int i=0; i<n; ++i )
{
    ....
}

This way, n remains unchanged. 这样, n保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM