This question already has an answer here:
- Sorting a vector of custom objects 13 answers
I have a class in which there is a variable of type int
stored inside. I have then created a vector which holds this class in it, which I then need to sort.
My problem however stems from the fact that I need to sort the vector using the values of the int stored inside of this class in accending order.
I have looked at the std::sort()
class built into C++ but cannot seem to get this to work. I have also looked at posts such as, Sorting a vector of custom objects
and have tried to use this, but with no avail.
As a side note, this is my first post, so if I am doing anything wrong, please let me know so that I can rectify the problem.
If you have a vector of your class object
And the variable to sort by is
Then you can
You just need to either implement an
operator<
for the class, or provide a comparison function for thestd::sort
:If you are using c++11, you can also provide a lambda as a comparison function: