STL 排序 - 调试断言失败

STL Sort - Debug Assertion Failed

C++ 中的计划。我使用 STL 排序和布尔比较器(此处为 cmp1cmp2 函数)对向量进行了排序。然而,在 运行 程序和读取向量的值时,它 returns: Debug Assertion Failed!, Line:1618, Expression: invalid comparator。这里,returns算法库错误的函数是:

// FUNCTION TEMPLATE _Debug_lt_pred
template <class _Pr, class _Ty1, class _Ty2,
    enable_if_t<is_same_v<_Remove_cvref_t<_Ty1>, _Remove_cvref_t<_Ty2>>, int> = 0>
constexpr bool _Debug_lt_pred(_Pr&& _Pred, _Ty1&& _Left, _Ty2&& _Right) noexcept(
    noexcept(_Pred(_Left, _Right)) && noexcept(_Pred(_Right, _Left))) {
    // test if _Pred(_Left, _Right) and _Pred is strict weak ordering, when the arguments are the cv-same-type
    const auto _Result = static_cast<bool>(_Pred(_Left, _Right));
    if (_Result) {
        _STL_VERIFY(!_Pred(_Right, _Left), "invalid comparator");
    }

    return _Result;
}

template <class _Pr, class _Ty1, class _Ty2,
    enable_if_t<!is_same_v<_Remove_cvref_t<_Ty1>, _Remove_cvref_t<_Ty2>>, int> = 0>
constexpr bool _Debug_lt_pred(_Pr&& _Pred, _Ty1&& _Left, _Ty2&& _Right) noexcept(noexcept(_Pred(_Left, _Right))) {
    // test if _Pred(_Left, _Right); no debug checks as the types differ
    return static_cast<bool>(_Pred(_Left, _Right));
}

这是我的程序:

#include <iostream>
#include <algorithm>
#define DIM 10006
using namespace std;

bool cmp1(int st, int dr) {
    return (st >= dr);
}

bool cmp2(int st, int dr) {
    return (st <= dr);
}

void Scan(int& n, int& m, char& c, int v[])
{
    cin >> n >> m >> c;
    for (int i = 0; i < n * m; i++)
        cin >> v[i];
}

void Print(int n, int m, int v[])
{
    int k = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << v[k] << ' ';
            k++;
        }
        cout << '\n';
    }
}

int main()
{
    int v[DIM];
    int n, m;
    char c;
    Scan(n, m, c, v);
    if (c == '+')
        sort(v, v + n * m, cmp1);
    else //c == '-'
        sort(v, v + n * m, cmp2);
    Print(n, m, v);
    return 0;
}

对于相等的元素,比较器必须 return 为假。变化

bool cmp1(int st, int dr) {
    return (st >= dr);
}

bool cmp2(int st, int dr) {
    return (st <= dr);
}

bool cmp1(int st, int dr) {
    return (st > dr);
}

bool cmp2(int st, int dr) {
    return (st < dr);
}

只有当第一个参数必须放在排序中的第二个参数之前时,比较器才应该 return 为真。如果它们 return 对于相等的参数为真,那么 一些 算法将进入一个循环,无休止地交换相等的元素。

今天第二次看到这个问题