Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erratic behavior of GCC's std::sort with lambdas

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;
}
like image 717
S. K. Avatar asked Nov 27 '22 16:11

S. K.


1 Answers

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.

like image 54
max66 Avatar answered Dec 07 '22 02:12

max66