3

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
2
  • What do left and right refer to? They may need to be updated after the sort. Commented Oct 24, 2015 at 4:51
  • That was for other parts of the code not listed here. I removed them to reduce confusion Commented Oct 24, 2015 at 5:06

2 Answers 2

6

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;
});
Sign up to request clarification or add additional context in comments.

5 Comments

Your first solution uses a pair of parenthesis for each pointer which is totally useless. Dereferencing a pointer does not require parenthesis.
I am attempting to get your solution to work, but as of yet, no luck
@Matt This requires C++11 or higher. VC does not have it; g++ use -std=c++11 option.
@dasblinkenlight I am using g++ with the -std=c++11 option
This works, it was user error on my part as to why it wasn't working for me. It's been a long night, thanks man.
0

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

1 Comment

You need to change &lhs and &rhs to *lhs and *rhs. By doing those changes, I was able to get this to work immediately

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.