網站首頁 編程語言 正文
刷題的時候經常會遇到需要自己寫一個sort比較函數,如果不知道怎么寫比較函數那就算你知道其中的算法邏輯也做不出題目,下面介紹一下幾種自定義的比較方法。
前置條件
- 注意C++sort是在algorithm這個包里的,注意include這個包
- sort的形式如下:注意只能對RandomAccessIterator 進行排序!!什么是RandomAccessIterator ?如果需要詳細的解釋參看:RandomAccessIterator cppreference,簡單說就是能夠以任意的偏移進行訪問的迭代器!如果不支持這樣的是不能夠用sort進行排序的!
Random-access iterators are iterators that can be used to access elements at an arbitrary offset position relative to the element they point to, offering the same functionality as pointers.
-
舉個例子,map里面的迭代器是Bidirectional iterators,只能支持迭代器++,–不支持+n這樣的任意偏移,就不能夠使用sort進行排序!
-
vector, deque支持RandomAccessIterator ,list, map, multimap, set and multiset只bidirectional iterators!
用法
std::sort
default (1)
template <class RandomAccessIterator> void sort (RandomAccessIterator first, RandomAccessIterator last);
custom (2)
template <class RandomAccessIterator, class Compare> void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
也就是有兩種,一種是采用不寫比較函數,另外一種是自定義比較函數。
注意:無論哪種前兩個參數都是RandomAccessIterator,也就是不能直接傳變量進去,必須是傳入相應的迭代器,這是新手一開始非常容易犯的錯誤。
Binary function that accepts two elements in the range as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
第1種直接寫比較函數
bool myfunction (int i,int j) { return (i<j); }
注意:這種比較函數必須寫在類外部(全局區域)或聲明為靜態函數!(我聽說是因為如果是作為一個成員函數,默認擁有一個this指針,和sort函數需要的函數對象類型不一樣)。
第2種定義一個結構體,構造一個函數對象(function object)也就是對運算符()進行重載,這就是相當于構造了一個函數對象
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
第3種采用lambada函數
對于簡單的函數比較,可以采用C++11的新特性lambada函數:
sort(msVector.begin(), msVector.end(), [](const MyStruct& ms1, const MyStruct& ms2){
return ms1.weight < ms2.weight;
});
可以參考:https://www.cnblogs.com/DswCnblog/p/5629165.html
第4種采用默認的less和greater
其實less和greater都是函數對象,即Function object,什么是function object?
Generically, function objects are instances of a class with member function operator() defined. This member function allows the object to be used with the same syntax as a function call.
可以看一下less的模板:
template <class T> struct less {
bool operator() (const T& x, const T& y) const {return x<y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
可以看出來實際上less也是重載了一個()運算符,注意less是表示第一個元素比第二個元素小,其實就是升序排列。
舉例:
// less example
#include <iostream> // std::cout
#include <functional> // std::less
#include <algorithm> // std::sort, std::includes
int main () {
int foo[]={10,20,5,15,25};
int bar[]={15,10,20};
std::sort (foo, foo+5, std::less<int>()); // 5 10 15 20 25
std::sort (bar, bar+3, std::less<int>()); // 10 15 20
if (std::includes (foo, foo+5, bar, bar+3, std::less<int>()))
std::cout << "foo includes bar.\n";
return 0;
}
同樣的,greater就表示降序排列,這是他的模板和應用示例。
模板:
template <class T> struct greater {
bool operator() (const T& x, const T& y) const {return x>y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
示例:
// greater example
#include <iostream> // std::cout
#include <functional> // std::greater
#include <algorithm> // std::sort
int main () {
int numbers[]={20,40,50,10,30};
std::sort (numbers, numbers+5, std::greater<int>());
for (int i=0; i<5; i++)
std::cout << numbers[i] << ' ';
std::cout << '\n';
return 0;
}
我個人建議還是采用第一種和第二種,第四種的方法,相對直觀,如果還有其他方法也歡迎討論。
原文鏈接:https://blog.csdn.net/Sansipi/article/details/127019948
相關推薦
- 2022-05-09 sql語句中union的用法與踩坑記錄_MsSql
- 2021-12-09 帶你一文了解C#中的LINQ_C#教程
- 2022-05-14 在Pandas?DataFrame中插入一列的方法實例_python
- 2022-10-26 Anaconda環境變量的配置圖文詳解_python
- 2023-01-20 redis數據傾斜處理方法_Redis
- 2022-01-16 ES6箭頭函數、rest參數、擴展運算符、Symbol的使用
- 2022-12-29 淺析Python是如何實現集合的_python
- 2022-11-17 Android顯式Intent與隱式Intent的使用詳解_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支