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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源链接:https://www.jb51.net/program/335160pg3.htm

© 版权声明
THE END
支持一下吧
点赞8 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容