如何对矢量<矢量进行排序<int>>

how to sort vector<vector<int>>

本文关键字:gt lt int 排序      更新时间:2023-10-16

我写了一个compare()函数来对vector< vector < int > >进行排序,结果它崩溃了。

具体来说,如果我调用sort(u.begin(),u.end());,则不会发生崩溃。然而,如果我调用sort(u.begin(),u.end(), compare);,它崩溃了,即使compare()只是返回true而没有更多的代码。我的代码出了什么问题?

bool compare_4sum(vector<int>& a, vector<int>& b){
    return true;
}
void test(){    
    vector<int> x; 
    x.push_back(1);
    x.push_back(2);
    vector<int> x2;
    x2.push_back(2);
    x2.push_back(4);    
    vector<vector<int>> u;    
    u.push_back(x);
    u.push_back(x2);
    sort(u.begin(),u.end(), compare);
}

您的比较函数必须提供严格的弱排序。如果没有,那么对sort的调用将显示未定义的行为。

25.4/3&4

3) 对于所有采用Compare的算法,有一个版本使用运算符<相反即comp(*i,*j)!=false默认为*i<j!=false。对于25.4.3中描述的算法以外的算法正确地说,comp必须对值进行严格的弱排序。

4) "严格"一词指的是不灵活的关系(!comp(x,x)表示所有x),以及弱于需求的术语它们没有完全订购的那么强大,但更强大而不是偏序。如果我们将equiv(a,b)定义为!comp(a,b)&amp!comp(b,a),则要求comp和等价都是传递关系:

— comp(a, b) && comp(b, c) implies comp(a, c)
— equiv(a, b) && equiv(b, c) implies equiv(a, c) [ Note: Under these conditions,
  it can be shown that
    — equiv is an equivalence relation
    — comp induces a well-defined relation on the equivalence classes determined
      by equiv
    — The induced relation is a strict total ordering. —end note ]

它可能会崩溃,因为排序的比较函数必须遵循严格的弱排序。你的比较几乎在所有账户上都失败了:

对于所有的x,不是x<x

这显然会失败。

对于所有x,y,如果x<则不是y<x

compare_4sum(x, y)将是truecompare_4sum(y, x)也是,因此打破了这一点。

依此类推。在编写用于std::sort的谓词时,必须非常小心,它们不会破坏此约定,否则很可能会崩溃。

此外,任何比较函数都不应该修改其运算的值,因此您应该始终传递const &,而不是&