如何使用 lambda 进行排序?

问题描述 投票:0回答:4
sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b)
{ 
    return a.mProperty > b.mProperty; 
});

我想使用 lambda 函数对自定义类进行排序,而不是绑定实例方法。但是,上面的代码会产生错误:

错误 C2564:“const char *”:到内置类型的函数式转换只能采用一个参数

boost::bind(&MyApp::myMethod, this, _1, _2)
配合使用效果很好。

c++ sorting lambda char constants
4个回答
238
投票

明白了。

升序:

std::ranges::sort(mMyClassVector, [](const MyClass &a, const MyClass &b)
{ 
    return a.mProperty < b.mProperty; 
});

降序:

std::ranges::sort(mMyClassVector, [](const MyClass &a, const MyClass &b)
{ 
    return a.mProperty > b.mProperty; 
});

当使用比

C++20
更旧的标准时,您可以使用

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

相反。


39
投票

你可以这样使用它:

#include<array>
#include<functional>
using namespace std;
int main()
{
    array<int, 10> arr = { 1,2,3,4,5,6,7,8,9 };

    sort(begin(arr), 
         end(arr), 
         [](int a, int b) {return a > b; });

    for (auto item : arr)
      cout << item << " ";

    return 0;
}

6
投票

问题可能出在“a.mProperty > b.mProperty”行吗?我已经得到了以下代码来工作:

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

输出为:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

3
投票

您可以像这样对数组进行排序:

#include <bits/stdc++.h>
using namespace std;
int main() {
    int q[] = {1, 3, 5, 7, 9, 2, 4, 6, 8 ,10};
    sort(q, q + 10, [&](int A, int B) { return A < B; });
    for (int i = 0; i < 10; i++)
        cout << q[i] << ' ';
    return 0;
}
before sort: 1 3 5 7 9 2 4 6 8 10
after sort: 1 2 3 4 5 6 7 8 9 10 

我总是喜欢在 acm 竞赛中使用 lambda 对结构体数组进行排序,如下所示:

struct item {
    int a, b;
};

vector<item> q;

sort(q.begin(), q.end(), [&](item t1, item t2) {
    return t1.a < t2.a;
});

© www.soinside.com 2019 - 2024. All rights reserved.