The following code generates a segmentation fault when compiled with GCC 6.1.0. Strangely, the error is consistent, but does not happen with smaller sizes or slightly different comparison expressions. Do you guys have any idea why?
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
int n = 1000;
std::vector<std::pair<double, double>> vec;
for(int i = 0; i < n; i++) {
vec.push_back(std::make_pair<double, double>((7*i)%3, (3*i)%5));
}
std::sort(vec.begin(), vec.end(), [](std::pair<double, double> const & p1, std::pair<double, double> const & p2) {return (p1.first < p2.first) || ((p1.first==p2.first)&& (p1.second <= p2.second));});
return 0;
}
Try changing
(p1.second <= p2.second)
with
(p1.second < p2.second)
I mean... std::sort()
need a comparator that return true
iff (if and only if) the first argument (p1
) is strictly lower than the second one (p2
). That is: must return false
when p1
is equal to p2
.
If your test is
(p1.first < p2.first)
|| ((p1.first==p2.first)&& (p1.second <= p2.second))
you obtain true
also when p1
is equal to p2
.
With a comparator that return true
when p1
is equal to p2
... if I'm not wrong the behavior is undefined so an "erratic behavior" (and a segmentation fault also) is absolutely understandable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With