c++ std::sort使用自定義的比較函數(shù)排序方式
使用sort對容器內(nèi)元素進行排序
- std::sort()函數(shù)專門用來對容器或普通數(shù)組中指定范圍內(nèi)的元素進行排序,排序規(guī)則默認(rèn)以元素值的大小做升序排序。
- sort() 只對 array、vector、deque 這 3 個容器提供支持
- 可以自定義排序函數(shù)
#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是我們自定義的函數(shù),sort 第三個三處
std::sort(vec.begin(), vec.end(), comparePairs);
在類中如何調(diào)用自定義的成員函數(shù)進行排序
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”: 非標(biāo)準(zhǔn)語法;請使用 "&" 來創(chuàng)建指向成員的指針
C2672 “std::sort”: 未找到匹配的重載函數(shù)
C2780 “void std::sort(const _RanIt,const _RanIt)”: 應(yīng)輸入 2 個參數(shù),卻提供了 3 個
錯誤原因
這個錯誤是因為在使用std::sort()時,傳遞了一個成員函數(shù)指針,而非普通函數(shù)指針
解決辦法
使用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); }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
- 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的區(qū)別解析
- C++中的std::funture和std::promise實例詳解
- C++中std::transform的使用小結(jié)
- C++?std::copy與memcpy區(qū)別小結(jié)
- C++實現(xiàn)std::set的示例項目
相關(guān)文章
C語言實現(xiàn)Linux下的socket文件傳輸實例
這篇文章主要介紹了C語言實現(xiàn)Linux下的socket文件傳輸?shù)姆椒?較為詳細(xì)的分析了C語言文件Socket文件傳輸客戶端與服務(wù)器端相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2015-06-06完美解決QT?QGraphicsView提升到QChartView報錯的問題
使用QT提供的QChartView來繪制圖表,提升QGraphicsView控件繼承QChartView后,然后將QGraphicsView提升到我們自己寫的類,怎么才能確保提升后編譯不報錯呢,下面小編給大家?guī)砹薗T QGraphicsView 提升到QChartView報錯解決方案,感興趣的朋友一起看看吧2023-05-05Opencv 馬賽克和毛玻璃效果與圖片融合的實現(xiàn)
這篇文章主要為大家詳細(xì)介紹了通過OpenCV實現(xiàn)馬賽克和毛玻璃濾鏡效果與圖片的融合,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11