tags:

views:

134

answers:

2

Hi,

I have an array of (4) floating point numbers and need to sort the array in descending order. I'm quite new to c++, and was wondering what would be the best way to do this?

Thanks.

+12  A: 

Use std::sort with a non-default comparator:

float data[SIZE];
data[0] = ...;
...

std::sort(data, data + size, std::greater<float>());
R Samuel Klatchko
@sth - forgot about that. Updated my answer...
R Samuel Klatchko
For the beginner, `std::sort` is defined in the `<algorithm>` header in STL. Of course if this is a homework exercise, you should probably implement your own `sort` function.
Johnsyweb
+1  A: 

Assuming the following:

float my_array[4];

You can sort it like so:

#include <algorithm>

// ... in your code somewhere
float* first(&my_array[0]);
float* last(first + 4);
std::sort(first, last);

Note that the second parameter (last) is pointing to one past the end of your 4-element array; this is the correct way to pass the end of your array to STL algorithms. From there you can then call:

std::reverse(first, last);

To reverse the contents of the array. You can also write a custom comparator for the sort routine, but I'd consider that a step above beginner-level STL; it's up to you.

fbrereto
You missed the "in descending order" part of the question.
pmr
@pmr: Fixed, thanks.
fbrereto