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++.