如何使用自定义std::sort函数

How to use custom std::sort function?

本文关键字:sort 函数 std 何使用 自定义      更新时间:2023-10-16

Hi我有一个指针向量,实际上每个指针都是一个数组,其中每个数组是:

int a,int b,大小可变的整数序列。

无序矢量示例:

rows[0] => points to [1,2,...]
rows[1] => points to [2,1,...]
rows[2] => points to [3,1,...]
rows[3] => points to [1,4,...]
rows[4] => points to [1,1,...]

输出示例:

rows[0] => points to [1,1,...]
rows[1] => points to [1,2,...]
rows[2] => points to [1,4,...]
rows[3] => points to [2,1,...]
rows[4] => points to [3,1,...]

我需要以这种方式对这个向量进行排序,我创建了以下自定义比较函数:

bool cmpRow(unsigned int *a, unsigned int *b)
{
    //Mesmo id word
    if(a[0] == b[0])
    {
        return (a[1] < b[1]);
    }
    else
    {
        return (a[0] < b[0]);
    }        
}

我使用它的方式如下:

std::vector<unsigned int*> rows;
.
.
//Insert some stuffs 
.
.
std::sort (rows.begin(), rows.end(), cmpRow);

但结果并不是我所期望的,有人能帮我解决这个问题吗?

编辑:

事实上,函数是可以的,问题出在循环中的一个函数中,这个函数调用排序函数的次数超过了必要的次数,所以结果不是预期的。

函数cmpRow根据前两个成员按升序对给定数组进行排序(首先比较第一个成员,如果它们相同,则比较第二个成员)。这可以很好地工作,并产生您报告的结果,根据该逻辑,这些结果是正确的。如果这不是预期的结果,会得到什么结果

这样更改代码?

bool cmpRow(unsigned int *a, unsigned int *b)
{
    //You need to safeguard against empty/equal rows

    //Mesmo id word
    if(a[0] == b[0])
    {
        return cmpRow(a[1] < b[1]);
    }
    else
    {
        return (a[0] < b[0]);
    }        
}