多属性排序是反转元素

Moo*_*oop 3 c++ sorting

我试图在一些数据上实现多属性排序,并通过背靠背来解决问题stable_sorts:

bool DecreasingA(const Data & a, const Data & b) {
    return a.A >= b.A;
}

bool DecreasingB(const Data & a, const Data & b) {
    if (a.B)
        return true;  // if a.B is true, maintain ordering
    if (b.B)
        return false; // a.B is false, but b.B is true, to swap elements
    return true;      // a.B and b.B are false, maintain ordering
}

std::vector<Data> myVector;

// add Data to vector here

std::stable_sort(myVector.begin(), myVector.end(), DecreasingA());
std::stable_sort(myVector.begin(), myVector.end(), DecreasingB());
Run Code Online (Sandbox Code Playgroud)

但是在我这样做之后,myVectorA属性的顺序与我想要的相反.即使它在第一个之后正确排序stable_sort

例如:

排序前:

A B C

1 0 5
1 1 8
2 0 2
0 1 3
Run Code Online (Sandbox Code Playgroud)

第一次排序(减少A)看起来很好:

A B C

2 0 2
1 0 5
1 1 8
0 1 3
Run Code Online (Sandbox Code Playgroud)

第二次排序后(减少B)我得到了这个:

A B C

0 1 3
1 1 8
1 0 5
2 0 2
Run Code Online (Sandbox Code Playgroud)

而不是我想要的:

A B C

1 1 8
0 1 3
2 0 2
1 0 5
Run Code Online (Sandbox Code Playgroud)

我认为这是我的DecreasingB功能的一个问题,但我已经尝试了各种逻辑并继续进行这种反转.有什么建议?

我知道我可以编写一个比较函数来处理这种特殊情况,但我需要灵活性让最终用户选择要排序的属性以及它们应用的顺序.

Ben*_*ley 6

您的比较功能都已损坏.两者都没有实现所需的严格弱排序std::stable_sort.特别,

  • 反身性:f(x, x)必须是假的.
  • 反对称:f(x, y)意味着!f(y, x)

两个帐户的功能都失败了.

你可能想要这个:

bool DecreasingA(const Data & a, const Data & b) {
    return a.A > b.A;  // > instead of >=
}

bool DecreasingB(const Data & a, const Data & b) {
    if (a.B == b.B)   // both equal, so a does not precede b
        return false;
    if (b.B)          // b.B is true and a.B is false, so a does not precede b
        return false; 
    return true;      // a.B is true and b.B is false, so a does precede b
}
Run Code Online (Sandbox Code Playgroud)