How to sort with a lambda?

后端 未结 3 2012
旧巷少年郎
旧巷少年郎 2020-12-12 12:51
sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b)
{ 
    return a.mProperty > b.mProperty; 
});


        
相关标签:
3条回答
  • 2020-12-12 13:14

    To much code, you can use it like this:

    #include<array>
    #include<functional>
    
    int main()
    {
        std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };
    
        std::sort(std::begin(vec), 
                  std::end(vec), 
                  [](int a, int b) {return a > b; });
    
        for (auto item : vec)
          std::cout << item << " ";
    
        return 0;
    }
    

    Replace "vec" with your class and that's it.

    0 讨论(0)
  • 2020-12-12 13:18

    Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

    #include <algorithm>
    #include <vector>
    #include <iterator>
    #include <iostream>
    #include <sstream>
    
    struct Foo
    {
        Foo() : _i(0) {};
    
        int _i;
    
        friend std::ostream& operator<<(std::ostream& os, const Foo& f)
        {
            os << f._i;
            return os;
        };
    };
    
    typedef std::vector<Foo> VectorT;
    
    std::string toString(const VectorT& v)
    {
        std::stringstream ss;
        std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
        return ss.str();
    };
    
    int main()
    {
    
        VectorT v(10);
        std::for_each(v.begin(), v.end(),
                [](Foo& f)
                {
                    f._i = rand() % 100;
                });
    
        std::cout << "before sort: " << toString(v) << "\n";
    
        sort(v.begin(), v.end(),
                [](const Foo& a, const Foo& b)
                {
                    return a._i > b._i;
                });
    
        std::cout << "after sort:  " << toString(v) << "\n";
        return 1;
    };
    

    The output is:

    before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
    after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,
    
    0 讨论(0)
  • 2020-12-12 13:19

    Got it.

    sort(mMyClassVector.begin(), mMyClassVector.end(), 
        [](const MyClass & a, const MyClass & b) -> bool
    { 
        return a.mProperty > b.mProperty; 
    });
    

    I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

    0 讨论(0)
提交回复
热议问题