简体   繁体   English

比较C ++ Stl排序中的函数

[英]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. 所以cmp(1,1)会产生不同的结果。

Undefined behavior: 未定义的行为:

Given this cmp() function: 鉴于此cmp()函数:

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 . 传递给std::sort的比较器是实现Compare所必需的。 One of the requirements is that cmp(1,1) will return false. 要求之一是cmp(1,1)将返回false。 Your code returns true. 您的代码返回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: 另外,鉴于这是C ++ 11,为什么不这样做:

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

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

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