简体   繁体   English

C ++ sort lambda比较器EXC_BAD_ACCESS

[英]C++ sort lambda comparator EXC_BAD_ACCESS

I experienced this weird issue that the following code throws EXC_BAD_ACCESS error. 我遇到了这个奇怪的问题,以下代码抛出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);
});

If I run: 如果我跑:

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

It works. 有用。 If I reduce the data size, it works too. 如果我减少数据大小,它也可以。 I am curious what does ((a.first == b.first) && a.second) do that caused the error? 我很好奇((a.first == b.first) && a.second)导致错误的是什么? Complete source code with data is here: https://pastebin.com/r7muQhu7 完整的数据源代码如下: https//pastebin.com/r7muQhu7

My environment: 我的环境:

Apple LLVM version 9.1.0 (clang-902.0.39.2)
Target: x86_64-apple-darwin17.7.0

Your lambda doesn't satisfy the conditions necessary for a sort comparison function, namely a comparison function must impose a strict weak ordering (although in practice you usually have a total ordering ). 你的lambda不满足排序比较函数所需的条件,即比较函数必须强加一个严格的弱排序 (尽管在实践中你通常有一个总排序 )。

Consider that in your case {1, true} is less than {1, true} , something can't be less than itself. 考虑到在你的情况下{1, true}小于{1, true} ,某些东西不能小于它自己。

This works 这有效

return (a.first < b.first) || ((a.first == b.first) && (a.second < b.second));

as does 同样如此

return (a.first < b.first) || ((a.first == b.first) && (a.second > b.second));

the following code throws EXC_BAD_ACCESS error [...] 以下代码抛出EXC_BAD_ACCESS错误[...]

I am curious what does ((a.first == b.first) && a.second) do that caused the error? 我很好奇((a.first == b.first) && a.second)导致错误的是什么?

The answer by @john solves the issue exactly the right way, and with good explanation, in terms of what the OP did wrong. @john的答案完全以正确的方式解决了这个问题,并且就OP的错误做了很好的解释。 Id like to add why specifically a EXC_BAD_ACCESS might have been thrown. 我想添加为什么可能会抛出EXC_BAD_ACCESS The reason in that std::sort() is usually implemented using Quick Sort , which is typically written in a recursive manner. std::sort()原因通常是使用Quick Sort实现的, Quick Sort通常以递归方式编写。 Hence, the fact that you didn't provide the strict (weak) ordering, could have definitely caused it to enter an endless recursion exactly at that point of comparison where something is less than itself. 因此,你没有提供严格(弱)排序的事实,肯定会导致它进入一个无休止的递归,恰好在某个比自己小的比较点。 ie the comparison will return true no matter the order of the operands. 即无论操作数的顺序如何,比较都将返回true。 This endless recursion is the direct cause of a stack overflow , as your program attempts to use more space than is available on the call stack . 这种无休止的递归是堆栈溢出的直接原因,因为您的程序试图使用比调用堆栈上可用空间更多的空间 In certain platforms this translates to a EXC_BAD_ACCESS signal. 在某些平台中,这转换为EXC_BAD_ACCESS信号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM