如何对矢量<矢量进行排序<int>>
how to sort vector<vector<int>>
我写了一个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)&!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)
将是true
,compare_4sum(y, x)
也是,因此打破了这一点。
依此类推。在编写用于std::sort
的谓词时,必须非常小心,它们不会破坏此约定,否则很可能会崩溃。
此外,任何比较函数都不应该修改其运算的值,因此您应该始终传递const &
,而不是&
。
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 如何防止clang格式在流运算符调用之间添加换行符<<
- <<操作员在下面的行中工作
- EASTL矢量<向量<int>>连续的
- C - 创建矢量&lt; vector&lt; double&gt;&gt;矩阵具有分配而不是inizializ
- 为什么将此对向量&lt; map&lt; int,int&gt;&gt;中的地图进行更新.失败
- C :对矢量进行排序&lt; struct&gt;(结构有2个整数)基于结构的整数之一
- 明确的专业化“ CheckIntmap&lt;&gt;”实例化
- 什么是模板&lt;&gt;inline bla bla
- 编辑C Qlist&lt; object*&gt; gt;QML代码和一些QML警告中的模型
- eigen :: llt&lt;eigen :: matrixxd&gt;具有不完整的类型
- 错误,包括&lt; ctype&gt;在原子上使用C 11
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- 如何加入向量&lt; int&gt;到C 中的单个INT
- 是std :: set&lt; std :: future&gt;不可能存在
- 是numeric_limits&lt; int&gt; :: is_modulo从逻辑上矛盾
- opencv 2.4.7在iOS错误背景_segm.hpp #include&lt; list&gt;未找到
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- ///<评论></评论>在Visual Studio中