c++ - Why doesn't this print anything on the screen? -
#include <iostream> using namespace std; class { public: int index; int t; int d; int sum; }; arr[1000]; bool comp (const &a, const &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; = 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); ( int j = 0; j < n; j++ ) cout<<arr[j].index; cout<<"\n"; return 0; }
so, made program accepts values users, , sorts them on basis of specific condition. however, when try print values of array, doesn't print it. don't know why. please help. thanks!
ps: tried print value of array without use of comparator function, still doesn't print.
edit: got error, mentioned amazing people in comments. however, on inputting values as,
5 8 1 4 2 5 6 3 1 4 3
it should return answer 4 2 5 1 3
instead returns 1 2 3 4 5
. basically, sorts according sum of 2 elements in each row , prints index. might problem?
it not sorting because modifying value of n
in while
loop.
so, when n = 0
after loop ends, there nothing sort (or print later matter):
sort( arr, arr + n, comp);
is equivalent
sort( arr, arr + 0, comp);
easiest approach use for
loop:
for( int i=0; i<n; ++i ) { .... }
this way, n
remains unchanged.
Comments
Post a Comment