2

I am trying to sort a vector elements by using lambda but I have a question. I am trying to sort it base on 2 values from a struct but lambda does not allow me to do it like that.

Here is what i am trying to do:

struct Test
{   int Current;
    int Max;
};

std::vector<Test*> VectorA

std::sort(VectorA.begin(), VectorA.end(), [](Test& test, Test& test2) {return (test.Current > test2.Current) && (test.Max > test2.Current); });

Is it possible to use it like that ?

4
  • 3
    Your vector contains Test*, not Test as your lambda implies. Commented Nov 6, 2022 at 16:22
  • 2
    Why does your lambda take non-const references as inputs? Do you intend to modify them? (Hopefully not) Commented Nov 6, 2022 at 16:24
  • 4
    Your comparaison doesn't comply with strict weak ordering neither. Commented Nov 6, 2022 at 16:29
  • thanks for telling me my mistakes i learned from it i am grateful for that i just started to learning c++ Commented Nov 6, 2022 at 19:17

1 Answer 1

3

Your std::vector contains elements of type Test*, not Test.
Therefore your lambda should accept references to Test* objects, and dereference the pointers with operator->.

Since you do not need to modify these objects, it is better for your lambda to accept the arguments by a const reference.

A complete example:

#include <vector>
#include <algorithm>

struct Test
{
    int Current;
    int Max;
};

int main()
{
    std::vector<Test*> VectorA;
    std::sort(VectorA.begin(), 
              VectorA.end(),
//---------------vvvvv--------------vvvvv--------------
              [](Test* const& test, Test* const& test2)
//----------------------------vv---------------vv-----------
                { return (test->Current > test2->Current) && (test->Max > test2->Current); });
    return 0;
}

Edit: my answer above addressed only the issue of the c++ syntax itself.

As commented below by @Jarod42, there is also a semantic issue here - your comparison logic does not comply with strict weak ordering (see: Wikipedia - Weak Ordering).

Sign up to request clarification or add additional context in comments.

3 Comments

Comparer is wrong too about strict weak ordering, maybe return std::tie(lhs.Current, lhs.Max) > std::tie(rhs.Current, rhs.Max);
@Jarod42 good point. I merely addressed the syntax issue. Updated my answer.
Thanks guys for helping me and thanks for explain and telling me my mistakes i am grateful for that

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.