3

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.

Community
  • 1
  • 1
Crimson
  • 149
  • 1
  • 1
  • 10

2 Answers2

14

If you have a vector of your class object

std::vector<MyClass> objs;

And the variable to sort by is

MyClass.value

Then you can

std::sort(objs.begin(),
          objs.end(),
          [](const MyClass& lhs, const MyClass& rhs)
{
    return lhs.value < rhs.value;
});
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • I have tried this "std::sort(NodeList.begin(), NodeList.end(), [](const Node& lhs, const Node& rhs){ lhs.F < rhs.F; });", however I get errors upon running my program. " '!' : illegal on operands of type 'void'" and "see reference to function template instantiation 'std::pair<_RanIt,_RanIt> std::_Unguarded_partition<_RanIt,_Pr>(_RanIt,_RanIt,_Pr)'" – Crimson Apr 16 '15 at 13:49
  • You are missing the `return` keyword – Cory Kramer Apr 16 '15 at 14:00
  • that did it, thanks heaps, however are you able to explain what the 3rd argument does so that I can learn from this? – Crimson Apr 16 '15 at 14:05
  • The 3rd argument is a [lambda expression](http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) and I used that so I didn't have to make a comparison functor like SingerOfTheFail's `compare` function. It is a nameless in-place function. – Cory Kramer Apr 16 '15 at 14:10
8

You just need to either implement an operator< for the class, or provide a comparison function for the std::sort:

class MyClass
{
public:
    MyClass(int val) : i(val){}
    bool operator<(const  MyClass & other) //(1)
    {
        return i < other.i;
    }

    int i;
};

bool compare(const MyClass & l, const MyClass & r) //(2)
{
    return l.i < r.i;
}


int main( int argc, char *argv[] )
{
    std::vector<MyClass> vec;
    vec.push_back(MyClass(5));
    vec.push_back(MyClass(1));
    vec.push_back(MyClass(3));
    std::sort(vec.begin(), vec.end());//works if operator < is present (1)
    std::sort(vec.begin(), vec.end(), compare);//works if comparison function is present (2)
}

If you are using c++11, you can also provide a lambda as a comparison function:

std::sort(vec.begin(), vec.end(), [](MyClass & one, MyClass & two){return one.i < two.i;});
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105