0

I'm trying to write a sort function for vectors using lambda, and I've seen this suggested at so many places, but I've always had problems doing this.

std::sort(eventvec.begin(), eventvec.end(), [](const event& lhs, const event& rhs) {
    return lhs.getim < rhs.getim;});

I had multiple errors while writing it and then I kind of stacked it on a function within a function as it needed a static function.

The functions declared in the class are:

double event::getut() { return unift; }

static double getim(event &a) { return a.getut(); }

In the end the sorting is not in order at all. There are negative values as well in the attribute. Any suggestions?

6
  • What kind of errors are there? I think you should be using return lhs.getim() < rhs.getim(); instead of what you wrote. Commented Oct 23, 2020 at 8:39
  • 1
    You're not calling the function. return lhs.getut() < rhs.getut() but that means you need to make getut() const. Like this: double event::getut() const { return unift; } Commented Oct 23, 2020 at 8:39
  • @TanveerBadar that would ask for arguments, and what do I enter as an argument because lhs.getim(lhs) doesn't work. Commented Oct 23, 2020 at 8:46
  • @RetiredNinja error: passing 'const event' as 'this' argument discards qualifiers [-fpermissive] AND --------------------------------------------------------------------------------------- note: in call to 'double event::getut()' double event::getut() ^~~~~ Commented Oct 23, 2020 at 8:47
  • You didn't read all of what I wrote. "that means you need to make getut() const. Like this: double event::getut() const { return unift; }" Commented Oct 23, 2020 at 9:01

1 Answer 1

3

You are sorting your events by the address of event::getim, which is the same for every event.

I think you mean to call a member function of event, which needs to be callable from a const event

double event::getut() const { return unift; }

std::sort(eventvec.begin(), eventvec.end(), [](const event& lhs, const event& rhs) {
return lhs.getut() < rhs.getut(); });
Sign up to request clarification or add additional context in comments.

2 Comments

@wakanada you need to edit event::getut as shown. It needs to be callable from const event
yeah, got it. Thanks

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.