Sort float array in C ++

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

Thank.

+5
source share
2 answers

Use std::sortwith a non-standard comparator:

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

std::sort(data, data + size, std::greater<float>());
+18
source

Assuming the following:

float my_array[4];

You can sort it like this:

#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) points to one end of the end of your 4-element array; this is the right way to pass the end of your array to STL algorithms. From there you can call:

std::reverse(first, last);

. sort, , STL ; .

+1

All Articles