C++ sort lambda比较器EXC_BAD_ACCESS

Cod*_*fox 3 c++ lambda exc-bad-access c++11

我遇到了这个奇怪的问题,以下代码抛出EXC_BAD_ACCESS错误.

using T = pair<int, bool>;
sort(vp.begin(), vp.end(), [](const T& a, const T& b) {
    return (a.first < b.first) || ((a.first == b.first) && a.second);
});
Run Code Online (Sandbox Code Playgroud)

如果我跑:

using T = pair<int, bool>;
sort(vp.begin(), vp.end(), [](const T& a, const T& b) {
    return (a.first < b.first);
});
Run Code Online (Sandbox Code Playgroud)

有用.如果我减少数据大小,它也可以.我很好奇是什么((a.first == b.first) && a.second)导致了这个错误?完整的数据源代码如下:https://pastebin.com/r7muQhu7

我的环境:

Apple LLVM version 9.1.0 (clang-902.0.39.2)
Target: x86_64-apple-darwin17.7.0
Run Code Online (Sandbox Code Playgroud)

joh*_*ohn 6

你的lambda不满足排序比较函数所需的条件,即比较函数必须强加一个严格的弱排序(尽管在实践中你通常有一个总排序).

考虑到在你的情况下{1, true}小于{1, true},有些东西不能比自己少.

这有效

return (a.first < b.first) || ((a.first == b.first) && (a.second < b.second));
Run Code Online (Sandbox Code Playgroud)

同样如此

return (a.first < b.first) || ((a.first == b.first) && (a.second > b.second));
Run Code Online (Sandbox Code Playgroud)