views:

467

answers:

5

I have a question regarding the std::sort algorithm. Here is my test code:

struct MyTest
{
    int m_first;
    int m_second;

    MyTest(int first = 0, int second = 0) : m_first(first), m_second(second)
    {
    }
};


int main(int argc,char *argv[])
{
    std::vector<MyTest> myVec;
    for(int i = 0; i < 10; ++i)
    {
     myVec.push_back(MyTest(i, i + 1));
    }


    //Sort the vector in descending order on m_first without using stand alone function or functors


    return 0;

}

Is it possible to sort the vector on the variable m_first without using any stand alone functions or functors? Also, please note that I am not using boost.

+3  A: 

Write an operator< for your struct. This is the default function used by sort and the easiest way to allow it to function on your custom data structures.

workmad3
+3  A: 

Define the operator<

struct MyTest
{
...
    bool operator<(const MyTest& a_test) const {
        return m_first < a_test.m_first;
    }
};
Igor Krivokon
The operator should only take one parameter and compare against "this".
sth
Yes, fixed, thanks!
Igor Krivokon
+9  A: 

Yes, so long as the value type in the range to be sorted has an operator < that defines a "strict weak ordering", that is to say, it can be used to compare two MyTest instances correctly. You might do something like:

class MyTest
{
  ...
  bool operator <(const MyTest &rhs) const
  {
    return m_first<rhs.m_first;
  }
};
1800 INFORMATION
this isn't valid C++ code.it has to return bool or something else
the_drow
oops fixed up now
1800 INFORMATION
thanks for the answer..but if in future if I want to sort on m_second then I have to provide the functor. Is that correct?
Naveen
If you need to perform some kind of sort one way now, and a sort on a different set of data at some other time, then you can also specify a functor for comparison. In that case the functor is used, instead of the built-in, so there is no conflict between the two. I'd suggest that if you need to, then you should probably remove the comparison operator in order to remove the possibility of confusion for client code
1800 INFORMATION
+1  A: 

You should define an operator< in MyTest and it should look like this:

bool operator<(const MyTest &other) const {
  return m_first < other.m_first;
};
sth
+2  A: 

It is possible to do it with a member function but the stand alone function is the way to go.

bool operator <(const MyTest &lhs, const MyTest &rhs)
{
    return lhs.m_first<rhs.m_first;
}

Why ..

Scott Meyers: How Non-Member Functions Improve Encapsulation

If you're writing a function that can be implemented as either a member or as a non-friend non-member, you should prefer to implement it as a non-member function. That decision increases class encapsulation. When you think encapsulation, you should think non-member functions.

Surprised? Read on

TimW