下面的比较器功能如何在c ++中工作? [英] How does below comparator function works in c++?

查看:51
本文介绍了下面的比较器功能如何在c ++中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool comp(int a,int b){

    if ((a > 0 && b > 0) || (a < 0 && b < 0))
        return false;

    if ((a > 0) && (b < 0))
        return false;
}

对于给定的包含正整数和负整数的数组,上述函数可用于重新排列数组,以使负整数后跟正整数,并保留元素的顺序.

To a given array, which contains positive and negative integers, the above function is useful to rearrange the array such that, negative integers followed by positive integers and it preserves the order of elements.

示例:

int arr [] = {1,2,-3,-1}, n=sizeof(arr)/sizeof(int);

sort(arr,arr+n, comp);

output : {-3,-1,1,2}

但是我无法理解它是如何工作的,有人可以解释吗?

But I am unable to understand how it is working, Could someone explain ?

推荐答案

您的断言有两个方面不正确:

Your assertions are incorrect on two counts:

    如果您了解我的意思,
  1. std :: sort 保证保留不需要排序的元素的顺序.

  1. std::sort is not guaranteed to preserve the order of elements that don't need sorting, if you get my meaning.

comp 函数的行为是 undefined ,因为它在所有控制路径上都没有明确的 return 值.

The behaviour of your comp function is undefined as it doesn't have an explicit return value on all control paths.

一种补救方法是使用 std :: stable_sort ,它会尽可能地保留元素的顺序.如果第一个参数为负,第二个参数为正(我们将0定义为正),则可以将比较器函数调整为 true :

One remedy is to use std::stable_sort which will preserve the order of elements as best it can. The comparator function can be adjusted such that it's true if the first argument is negative and the second is positive (let's define 0 to be positive):

bool comp(int a, int b){
    return a < 0 && b >= 0;
}

另一种补救方法是使用 std :: stable_partition .

Another remedy is to use std::stable_partition.

这篇关于下面的比较器功能如何在c ++中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆