c++ std::sort使用自定义的比较函数排序

使用sort对容器内元素进行排序

  • std::sort()函数专门用来对容器或普通数组中指定范围内的元素进行排序,排序规则默认以元素值的大小做升序排序。
  • sort() 只对 array、vector、deque 这 3 个容器提供支持
  • 可以自定义排序函数
#include <iostream>
#include <vector>
#include <algorithm>

// Define the pair type
typedef std::pair<uint32_t, uint64_t> PairType;

// Comparator function to compare pairs based on the second element (value)
bool comparePairs(const PairType& p1, const PairType& p2) {
    return p1.second > p2.second;
}

int main() {
    // Create the vector of pairs
    std::vector<PairType> vec = {
        {1, 100},   // idx=1, value=100
        {2, 50},    // idx=2, value=50
        {3, 200},   // idx=3, value=200
        // Add more pairs here if needed
    };

    // Sort the vector using the comparator function
    std::sort(vec.begin(), vec.end(), comparePairs);

    // Output the sorted vector
    for (const auto& pair : vec) {
        std::cout << "idx: " << pair.first << ", value: " << pair.second << std::endl;
    }

    return 0;
}

comparePairs是我们自定义的函数,sort 第三个三处

 std::sort(vec.begin(), vec.end(), comparePairs);

在类中如何调用自定义的成员函数进行排序

typedef std::pair<uint32_t, uint64_t> PairType;

bool MySort::comparePairs(const PairType& p1, const PairType& p2) {
    return p1.second > p2.second;
}

bool MySort::sort_fun(vector<PairType> vec)
{
	std::sort(vec.begin(), vec.end(), comparePairs); //报错
}

Visual Studio 报错:

C3867	“MySort::compareParis”: 非标准语法;请使用 "&" 来创建指向成员的指针
C2672	“std::sort”: 未找到匹配的重载函数
C2780	“void std::sort(const _RanIt,const _RanIt)”: 应输入 2 个参数,却提供了 3

错误原因:

这个错误是因为在使用std::sort()时,传递了一个成员函数指针,而非普通函数指针

解决办法:使用Lambda表达式:

修改后的代码:

typedef std::pair<uint32_t, uint64_t> PairType;

bool MySort::comparePairs(const PairType& p1, const PairType& p2) {
    return p1.second > p2.second;
}

bool MySort::sort_fun(vector<PairType> vec)
{
	// 定义Lambda表达式
	auto sortLambda = [this](const PairType& p1, const PairType& p2) {
        return this->comparePairs(a, b);
    };
    
	std::sort(vec.begin(), vec.end(), sortLambda); 
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值