1

I have a struct:

struct particle {
double x;
double y;
double Th;
double wt;
};

I also have a vector vector<particle> vecHow do I sort the vector vec according to increasing data member wtI want my vector sorted with increasing double wtI thought of using std::sort but how do I compensate for the struct?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • You overload the operator< http://en.cppreference.com/w/cpp/language/operators – Pablo Oliva Jan 19 '18 at 14:10
  • You can pass a comparison function (or object) to `std::sort`, or define `operator<` for your struct. See [here](http://en.cppreference.com/w/cpp/algorithm/sort) for details. – molbdnilo Jan 19 '18 at 14:11

1 Answers1

3

It is actually quite easy:

std::sort(vec.begin(), vec.end(), 
    [](const particle& a, const particle& b) -> bool 
    { 
        return a.wt < b.wt;
    } 

This sorts the vector, based on the value of wt, in increasing order.

You also have another option: Defining operator< for particle, as follows:

bool operator<(const particle& a, const particle& b)
{
    return a.wt < b.wt;
}

Then, when calling std::sort, you can just do:

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

With the code above, std::sort will call operator< on each pair of particles, which now have overloads to compare them as such.

If you noticed, the lambda I used in the beginning is the same as the function overload I used above. This easily illustrates the beauty and flexibility of the STL and C++.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88