segmentation fault on std::sort with lambda expression

Hello,

I am geting segmentattion fault at run time when I compile my code with gcc and g++ on a linux system. But, I don't have this problem when I compile it with clang and clang++ on a Mac system.

My I code is too long to be written here. But I wrote an example which is similar to what I have.

Segmentation fault happens when a.a1 is empty. However, when I am filling the
galaxy struct I have check points to make sure a1 and a2 are not empty.

Any suggestion?

thank you in advance,
/M

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  typedef struct {
    std::string  a1, a2;   
} star

typedef struct {
    std::string  b1, b2;   
} planet

typedef struct {
    std::vector<star>   star;
    std::vector<planet> planet;
} galaxy;

std::sort(galaxy->star.begin(), galaxy->star.end(),
              [](const star &a, const star &b)
              {
                  return a.a1.compare(b.a1);
            
              });
The comparison function that you pass to std::sort is supposed to return true if the first operand is to be ordered before the second operand, otherwise it should return false.

std::string::compare returns zero (treated as false) if the two strings are equal, otherwise it returns a non-zero value (treated as true). This is not what the sort function expects.

You probably want to use the less than (or greater than) operator.

 
return a.a1.compare(b.a1) < 0;

You can make it a bit shorter by applying the less than operator directly on the two strings without using compare.

 
return a.a1 < b.a1;
Last edited on
1
2
 std::vector<star>   star;
    std::vector<planet> planet

Hard to keep track b/w the data-type and its variables ...
Topic archived. No new replies allowed.