Home > other >  sort vector by using lambda with &&
sort vector by using lambda with &&

Time:11-07

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 ?

CodePudding user response:

Your std::vector contains elements of type Test*, not Test.
Therefore your lambda should accept references to Test* objects, and derefernce 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 comparisson logic does not comply with strict weak ordering (see: Wikipedia - Weak Ordering).

  •  Tags:  
  • c
  • Related