comparing integers in an array

hey all!

I need to somehow compare integers in an array to later print them out from highest to lowest

this is how i input them

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, char *argv[])
{
    istream in("input.txt");
    int num;
    in>>num;
    int a[100];
    for (int i = 0;i <= num; i++){
        cin>>a[i];
        }
}


i first get the number of integers that will be compared, for example 4, then i just add them to the array.

How can i compare a variable amount of integers in an array with each other, then print them out from highest to lowest?
Please help! :(
You can use sort() function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <algorithm>

bool cmp_fn(int a,int b)
{
    return a>b;
}

int main() {
  int array[] = { 1,10,21,55,665,556 };

  int elements = sizeof(array) / sizeof(array[0]); // Get number of elements in array

  std::sort(array, array + elements,cmp_fn);

  for (int i = 0; i < elements; ++i) // print the results
     std::cout << array[i] << ' ';
}


http://www.cplusplus.com/reference/algorithm/sort/
I would use some kind of sort function. Maybe something like bubblesort (this is a simple way to sort but not the fastest) is what you're seeking. I forget how the code goes but i'm sure you can find it by searching for the function on google.
ok i've got this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
bool cmp_fn(int a,int b)
{
    return a>b;
}
int main(int argc, char *argv[])
{
    ifstream in("input.txt");
    int num;
    in>>num;
    int a[100];
    for (int i = 0;i <= num; i++){
        in>>a[i];
        }
   // Get number of elements in array

  sort(a, a + num,cmp_fn);

  for (int i = 0; i < num; ++i) // print the results
     cout << a[i] << ' ';
system("pause");
}


now it prints the integers in the array sorted from highest to lowest.
How to change the code so it would print the locations of the numbers in the array instead of the numbers itselfs?
for example, if i type in

4 //the number of integers in the array
11 //the integers
31
26
48

so instead of printing out
48
31
26
11

it would print out

4
2
3
1

?
Anyone? I really need this
for that you can use a class:
e.g.
1
2
3
4
5
6
7
8
class D
{
public:
  D() : index(0), value(0) { }

  int index;
  int value;
};

line 6 - 9
1
2
3
4
bool cmp_fn(const D &a, const D &b)
{
    return a.value>b.value;
}

line 17: in>>a[i].value; a[i].index=i;
line 24: cout << a[i].index << ' ';
Topic archived. No new replies allowed.