GCC std :: sort error behavior with lambdas

The following code generates a segmentation error when compiling with GCC 6.1.0. Oddly enough, the error is consistent, but does not occur with smaller sizes or slightly different comparison expressions. Do you guys know 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;
}
+4
source share
3 answers

Try to change

(p1.second <= p2.second)

with

(p1.second < p2.second)

I mean ... we std::sort()need a comparator that returns trueiff (if and only if) the first argument ( p1) is strictly lower than the second ( p2). That is: must return falsewhen p1equal p2.

If your test

   (p1.first < p2.first)
|| ((p1.first==p2.first)&& (p1.second <= p2.second))

you get truewell when p1equal p2.

, true, p1 p2... , undefined, " " ( ) .

+13

, Compare, :

  • , !comp(x, x) true x , (), comp(x, x) == true x (x.first == x.first && x.second <= x.second).

p1.second <= p2.second p1.second < p2.second, std::pair:

std::sort(vec.begin(), vec.end());
+11

Libstd++ , , _GLIBCXX_DEBUG.

$ g++-6 b.cc -D_GLIBCXX_DEBUG && ./a.out
/usr/include/c++/6/bits/stl_algo.h:4737:
Error: comparison doesn't meet irreflexive requirements, assert(!(a < a)).

Objects involved in the operation:
    instance "functor" @ 0x0x7ffe48ba5a20 {
      type = main::{lambda(std::pair<double, double> const&, std::pair<double, double> const&)#1};
    }
    iterator::value_type "ordered type" {
      type = std::pair<double, double>;
    }
+2

Source: https://habr.com/ru/post/1687244/


All Articles