在多列上对二维数组排序 [英] Sorting a 2 dimensional array on multiple columns
问题描述
我需要使用C或C ++在多列上对二维双精度数组进行排序。有人可以指出我应该使用的算法还是具有此功能的现有库(也许是增强功能?)?
I need to sort a 2 dimensional array of doubles on multiple columns using either C or C++. Could someone point me to the algorithm that I should use or an existing library (perhaps boost?) that has this functionality?
我感觉写递归函数可能可以走,但我懒得写出算法或自己实现(如果它已在其他地方实现)。 :-)
I have a feeling that writing a recursive function may be the way to go but I am too lazy to write out the algorithm or implement it myself if it has been done elsewhere. :-)
谢谢
推荐答案
您可以使用 std :: sort
(C ++ )或 qsort
(C或C ++)来执行排序操作。棘手的部分是您需要定义一个自定义比较函数来比较行。例如:
You can use std::sort
(C++) or qsort
(C or C++) to perform the sorting operation. The tricky part is that you need to define a custom comparison function for comparing your rows. For example:
bool compareTwoRows(double* rowA, double* rowB){
return ( (rowA[0]<rowB[0]) || ((rowA[0]==rowB[0])&&(rowA[1]<rowB[1])) );
}
// ...
double** two_dimensional_array = // ...
int rows = // ... number of rows ...
std::sort(two_dimensional_array,two_dimensional_array+rows,&compareTwoRows);
// ...
这篇关于在多列上对二维数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!