Alessandro
Alessandro

Reputation: 85

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.

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.

Upvotes: 0

Views: 1023

Answers (2)

aldo
aldo

Reputation: 2987

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). 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?

Upvotes: 1

nakiya
nakiya

Reputation: 14423

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

Upvotes: -1

Related Questions