0

I am trying to sort a vector<vector<int>> array using sort as follows:

sort(ed.begin(),ed.end(),[](vector<int> a,vector<int> b){return a[2]<=b[2];}  

Here ed is my array( of arrays ) and each element in this array is of size 3. So I am kinda sorting triplets with respect to last element. But this gives a segmentation fault at this very line of code. I tried to research on this and what I could find is something about strict weak ordering required in comparison function. So I then changed the sort statement as follows:

sort(ed.begin(),ed.end(),[](vector<int> a,vector<int> b){return a[2]<b[2];})  

Basically I just removed the equality sign from the comparison function. And this worked. So I want to know why this works and the previous one does not.

Just to let you know the complete picture, I am trying to implement kruskal's algorithm and "ed" is an array of edges. Each edge is a triplet <from,to,weight>.

moooeeeep
  • 31,622
  • 22
  • 98
  • 187
mman
  • 9
  • 1
    You need to provide a [Minimal, Complete, and Verifiable](https://stackoverflow.com/help/mcve) example, but my best guess is that not all elements of the array have at least 3 elements – Krzysztof Sakowski Jun 09 '18 at 18:55
  • 1
    It's just that `std::sort` needs a sorter which follows the strict weak ordering rule. That's all. – DimChtz Jun 09 '18 at 18:56
  • 3
    Please take those vectors a and b by const reference. – rustyx Jun 09 '18 at 18:59

0 Answers0