Matt
Matt

Reputation: 33

Sorting a Vector of Custom Objects by overloading <

I am trying to sort a vector of nodes. I followed the advice from this thread and overloaded my
struct's < operator. However I am not getting a sorted list after sort is called.

struct node
{

    int frequency ;
    char data;

    bool operator < (const node& n1) const
    {
        return (frequency < n1.frequency);
    }
};

I call sort by the following:

vector<node*> test
//fill test with nodes
sort(test.begin(),test.end());

Output:

Presort data is: 1,1,2,3,3,1,2,1,1
Postsort data is: 3,2,1,1,1,1,2,1,3

Upvotes: 3

Views: 1152

Answers (2)

doug
doug

Reputation: 4299

Easiest way to do this is to use lambdas:

sort(test.begin(),test.end(), [](const node &lhs, const node &rhs){return lhs->frequency < rhs->frequency;});

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

Since you are sorting a vector of pointers, but the operator applies to a struct, C++ ignores your operator < overload.

You can supply a custom comparer that calls your operator <, like this

std::sort(test.begin(), test.end(), [](const node* pa, const node* pb) {
    return (*pb) < (*pa);
});

or code the comparison straight into the lambda, and drop the unused overload of <, like this:

std::sort(test.begin(), test.end(), [](const node* pa, const node* pb) {
    return pb->frequency < pa->frequency;
});

Upvotes: 6

Related Questions