简体   繁体   中英

Compare function in c++ stl sort

I need to obtain an non-increasing order from a given random ordered elements.After working a lot, I realized that both the following codes produce different outputs. Why the codes produce different outputs?

bool cmp(int i,int j)
{
    if(i<j)
        return 0;
    return 1;
}
bool cmp(int i,int j)
{
   return i>j;
}

First function should be

bool cmp(int i,int j)
{
    if(i>j)
        return 1;
    return 0;
}

to get equivalent outputs.

Or alternatively use the following function:

bool cmp(int i,int j)
{
    return -1 * i < -1 * j;
}

First things first:

Your two functions produce different results when they have the same input. So cmp(1,1) produces different results.

Undefined behavior:

Given this cmp() function:

bool cmp(int i,int j) {
    if(i<j)
        return 0;
    return 1;
}

The following statement will produce undefined behavior :

std::vector<int> x;
std::sort(x.begin(), x.end(), cmp);

The comparator passed to std::sort is required to implement Compare . One of the requirements is that cmp(1,1) will return false. Your code returns true.

Your first function is equivalent to "not less than" ie "greater or equal" when what you want is "greater". Also, given that this is C++11, why not just do:

std::sort(v.begin(), v.end(), std::greater<int>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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