Sort a vector of struct based on a specific field

前端 未结 3 1155
星月不相逢
星月不相逢 2021-01-13 22:18

Currently I am trying to sort a vector of structs based on a specific field. I have set up a custom comparison function for the use of the sort function. However, i am getti

相关标签:
3条回答
  • 2021-01-13 22:53

    a) Use sort function with lambda notation as below( if you are using c++11)

     sort(vecData.begin(),vecData.end(), [](const Play &x, const Play &y){ return (x.relevance < y.relevance);});
    

    Working code:

    http://ideone.com/bDOrBV

    b) Make comparator function as static

    http://ideone.com/0HsaaH

    0 讨论(0)
  • 2021-01-13 22:55

    Although this is an old question, I would like to note for the benefit of the future readers the possibility of directly sorting according to a specific field with the help of projections in the upcoming Ranges library in C++20:

    ranges::sort(vecData, ranges::less, &Play::relevance);
    

    This avoids the need of specifying two iterators or writing a custom comparison function or lambda.

    0 讨论(0)
  • 2021-01-13 23:11
    static bool customCompare(const Play &x, const Play &y)
    
    0 讨论(0)
提交回复
热议问题