Sort
默认使用less排序,从小到大排序,可以自定义排序方法
- less() //从小到大排序 <
- grater() //从大到小排序 >
- less_equal() // <=
- gtater_equal()// >=
>从大到小排序 <从小到大排序
static bool cmp2(int a,int b){ return a > b;} // >从大到小排序 <从小到大排序
Priority_queue
priority_queue< int, vector<int>, cmp> pq;
三个参数 数据类型,存储数据的容器,比较函数
默认使用less排序,但是优先队列的less和sort的less是相反的,
在优先队列中,less排序,在出队列时,按照从大到小出列
greater按照从小到大出队列
>最小堆 <最大堆
// 最大堆的比较函数 改成> 就是最小堆
struct cmp{
bool operator()(int a,int b){
return a%10 < b%10;
}
};
完整代码
#include <iostream>
#include <queue>
#include <vector>
#include <unordered_map>
#include <cmath>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Solution {
public:
struct cmp{
bool operator()(int a,int b){
return a%10 < b%10;
}
};
static bool cmp2(int a,int b){ return a%10 > b%10;}
// 优先队列实现的比较函数
vector<int> RandomSample(vector<int> v){
vector<int> res;
priority_queue< int, vector<int>, cmp> pq;
for(auto i:v){
pq.push(i);
}
while(!pq.empty()){
res.push_back(pq.top());
pq.pop();
}
return res;
}
// 修改sort的内置比较函数
vector<int> RandomSample_v2(vector<int> v){
sort(v.begin(),v.end(),cmp2);
return v;
}
};
void Print_Vec(vector<int> a){
cout<<"[";
for(auto i:a)
cout<<i<<" ";
cout<<"]"<<endl;
}
vector<int> Rand(int s,int e,int n){
vector<int> res;
for(int i=0;i<n;i++)
{
int a = s + rand()%(e-s);
res.push_back(a);
}
return res;
}
int main() {
vector<int> rand_seed = Rand(0,50,10);
Print_Vec(rand_seed);
Print_Vec(Solution().RandomSample(rand_seed));
Print_Vec(Solution().RandomSample_v2(rand_seed));
clock_t start,end;
start = clock();
for (int i = 0; i < 1000000; i++)
{
i++;
}
end = clock();
cout << "Totle Time : " <<(double)(end - start)*1000 / CLOCKS_PER_SEC << "ms" << endl;
return 0;
}