开发者

sort an array of floats in c++

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 thi开发者_StackOverflow中文版s?

Thanks.


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

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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜