Question

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.

Was it helpful?

Solution

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;
  }
};

OTHER TIPS

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.

Define the operator<

struct MyTest
{
...
    bool operator<(const MyTest& a_test) const {
        return m_first < a_test.m_first;
    }
};

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

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;
};

http://ideone.com/3QLtP

This defines no operator <, but does define functor.

However, it's fun to travel through time or compilation process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top