开发者

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

目录
  • 使用sort对容器内元素进行排序
  • 在类中如何调python用自定义的成员函数进行排序
    • 错误原因
    • 解决办法
  • 总结

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

    • std::sort()函数专门用来对容器或普通数组中指定范围内的元素进行排序,排序规则默认以元素值的大小做升序排序。
    • sort() 只对 array、vectorphp、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 <<php; ", value: " << pair.second << std::endl;
        }
    
        return 0;
    }
    

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

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

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

    typedef stjavascriptd::pair<uint32_t, uint64_t> PairType;
    
    bool MySort::comparePairs(const Pwww.devze.comairType& 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); 
    }
    
    

    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

    0

    上一篇:

    下一篇:

    精彩评论

    暂无评论...
    验证码 换一张
    取 消

    最新开发

    开发排行榜