使用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
© 版权声明
本站所有资源来自于网络,仅供学习与参考,请勿用于商业用途,否则产生的一切后果将由您(转载者)自己承担!
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
THE END
暂无评论内容