Sort / stable_sort自定义比较功能会引起一些奇怪的问题

问题描述 投票:0回答:1

我对sort / stable_sort API的自定义函数具有非常基本的经验。以下是我在Windows Visual Studio 2017下运行的源代码。请帮助分析问题所在,我会错过任何事情还是背后的理论是什么?感谢您的帮助

// 10_3_1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;
#define MAX_INPUT_NO    (10u)

typedef bool(* sort_func_t)(const int input_a, const int input_b);

bool is_shorter(const int input_a, const int input_b)
{
#if 0
    //this portion will show the iteration overlap
    if (input_a > input_b)
        return false;
    else
        return true;
#else
    //both below works
    //return input_a < input_b;
    return input_a > input_b;

#endif
}

void elimDups(vector<int> &dat, sort_func_t func)
{
    vector<int>::iterator temp = dat.begin();
    std::stable_sort(dat.begin(), dat.end(), func);
    //sort(dat.begin(), dat.end());

    temp = unique(dat.begin(), dat.end());
    dat.erase(temp, dat.end());
}

void print_vec(vector<int> &dat)
{
    vector<int>::const_iterator index = dat.cbegin();
    int i = 0;
    for (; index < dat.cend(); index++)
    {
        cout << "dat[" << i << "] = " << dat.at(i++) << endl;
    }
}

int main()
{
    vector<int> a;
    int ia[MAX_INPUT_NO] = {0, 1, 2, 1, 2, 3, 1, 2, 4, 5};
    a.assign(ia, ia + MAX_INPUT_NO);
    print_vec(a);
    elimDups(a, is_shorter);
    print_vec(a);

    getchar();
    return 0;
}

但是当我使用if-else部分时,我遇到的问题是,它给了我无效的比较器断言错误。

  1. 如果我像下面那样定义自定义函数,则使用if-else模式,它可以正常工作。
bool is_shorter(const int input_a, const int input_b)
{
#if 1
    //this portion will show the iteration overlap
    if (input_a > input_b)
        return true;
    else
        return false;
#else
    //below works
    return input_a > input_b;
#endif
}

下面是我得到的结果。

预期项目1的结果

“”

  1. 如果我像下面那样定义自定义比较器函数,它也会使用if-else模式,它将因“无效的比较器”错误而失败。
bool is_shorter(const int input_a, const int input_b)
{
#if 1
    //this portion will show the iteration overlap
    if (input_a > input_b)
        return false;
    else
        return true;
#else
    //below works
    return input_a > input_b;
#endif
}

下面是我收到的错误消息:

来自Visual Studio 2017的错误消息

“”

  1. 但是如果我只使用return,那么它在两个方向上都可以正常工作。
bool is_shorter(const int input_a, const int input_b)
{
#if 0
    //this portion will show the iteration overlap
    if (input_a > input_b)
        return false;
    else
        return true;
#else
    //both below works
    //return input_a < input_b;
    return input_a > input_b;

#endif
}
c++ sorting comparator
1个回答
0
投票

此代码:

if (input_a > input_b)
    return false;
else
    return true;

是一种复杂的说法:

return !(input_a > input_b);

greater then的否定是less or equal

return input_a <= input_b; // logically same as before

问题是您不能使用less or equal关系进行排序,因为它没有提供算法要求的严格弱排序。您可以减少使用:

return input_a < input_b;

或大于您在代码中使用的代码。

© www.soinside.com 2019 - 2024. All rights reserved.