How does one go about sorting a vector containing custom (i.e. user defined) objects.
Probably, standard STL algorithm sort along with a predicate (a function or a function object) which would operate on one of the fields (as a key for sorting) in the custom object should be used.
Am I on the right track?
C++ – Sorting a vector of custom objects
csortingstl
Best Answer
A simple example using
std::sort
Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the
operator<
forMyStruct
:Using this method means you can simply sort the vector as follows:
Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a
>
operator and changing call of sort a bit:And you should call sort as: