c++ std::sort使用自定义的比较函数排序方式
作者:wjjontheway
文章介绍了使用std::sort对容器内元素进行排序的基本方法,包括自定义排序函数和在类中调用自定义成员函数进行排序的方法,文章还指出了在传递成员函数指针时可能会遇到的错误,并提供了使用Lambda表达式的解决办法
使用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); }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- C++中std::setw()的用法解读
- c++中std::placeholders的使用方法
- C++中std::thread{}和std::thread()用法
- C++中std::tuple和std::pair的高级用法
- c++之std::get_time和std::put_time
- C++中std::ios_base::floatfield报错已解决
- C++中std::invalid_argument报错解决
- C++中std::ifstream::readsome和std::ifstream::read的区别解析
- C++中的std::funture和std::promise实例详解
- C++中std::transform的使用小结
- C++ std::copy与memcpy区别小结
- C++实现std::set的示例项目