Sorting a vector of objects by a property of the object

后端 未结 4 698
春和景丽
春和景丽 2020-12-01 15:03

I\'m working on a project for school and need to sort some data. I\'ve been given a vector of objects and I have to sort the objects (either in place or using an index) base

4条回答
  •  情话喂你
    2020-12-01 15:49

    Use std::sort and a functor. e.g:

    struct SortByX
    {
       bool operator() const (MyClass const & L, MyClass const & R) { return L.x < R.x; }
    };
    
    std::sort(vec.begin(), vec.end(), SortByX());
    

    The functor's operator() should return true if L is less than R for the sort order you desire.

提交回复
热议问题