简体   繁体   English

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

[英]How to use custom std::sort function?

Hi i have a vector of pointers, actually each pointer is an array, where each arrays is: 嗨,我有一个指针向量,实际上每个指针是一个数组,其中每个数组是:

int a, int b, sequence of integers of variable size. int a,int b,可变大小的整数序列。

Example of unordered vector: 无序向量的示例:

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,...]

Example of output: 输出示例:

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,...]

I need to sort this vector in this way I create the following custom compare function: 我需要以此方式对向量进行排序,以创建以下自定义比较函数:

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]);
    }        
}

and I'm using it the following way: 我以下列方式使用它:

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

But the result isn't was I expected, can anyone help me with this issue? 但是结果出乎我的意料,有人可以帮助我解决这个问题吗?

Edit: 编辑:

Actually the functions is alright, the problem was in a function inside a loop, this functions called the sort function more times than the necessary so the result wasn't the expected. 实际上这些功能还不错,问题出在循环内的一个函数中,该函数称为sort函数的次数比必需的次数多,因此结果不是预期的。

Your function cmpRow sorts the given arrays in ascending order based on the first two members (by first comparing the first members, and if they are the same then comparing the second members). 您的函数cmpRow根据前两个成员以升序对给定的数组进行排序(首先比较第一个成员,如果它们相同,则比较第二个成员)。 This works fine and produces the results you reported, which are correct according to that logic. 这可以正常工作,并产生您报告的结果,根据该逻辑,结果是正确的。 If this was not the expected result, what result did you expect? 如果这不是预期的结果, 期待什么结果呢?

Change your code like this? 像这样更改您的代码?

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]);
    }        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM