【C++笔试】可以实现自动排序的函数/结构

优先队列: 底层是通过堆来实现

利用priority_queue函数,需添加头文件queue
向堆中添加数据使用push(),弹出数据为pop(),顶部数据为top(),判断是否为空empty(),示例如下:

#include <queue>
#include <vector>

int main(){
    //从大到小,大根堆: less
	priority_queue<int, vector<int>, less<int> > heap;
	//从小到大,小根堆: greater
	//priority_queue<int, vector<int>, greater<int> > heap2;
	heap.push(8);
	heap.push(4);
	heap.push(9);
	heap.push(3);
	heap.push(0);
	while (!heap.empty()) {
		cout << heap.top() << endl;
		heap.pop();
	}
	//大根堆:9 8 4 3 0
	//小根堆:0 3 4 8 9
	return 0;
}

重载queue中的比较器

#include <queue>
#include <vector>
using namespace std;
struct Node{
    int value;
    int nums;
    Node(int val, int n){
        value = val;
        nums = n;
    }
};
struct heapCom{
	bool operator(const Node& A, const Node& B) const{
		return A->nums < B->nums;
	}
};

排序函数:sort

需添加头文件algorithm;
时间复杂度为O(N*logN),排序的区间是**[a,b)**,默认是升序:从小到大

#include <algorithm>
#include <vector>

int main(){
    vector<int> arr = { 3,8,0,4,7 };
    sort(arr.begin(), arr.end());//arr: 0 3 4 7 8
    sort(arr.begin(), arr.end(), greater<int>());//arr: 8 7 4 3 0
	return 0;
}

sort重载比较运算

#include <iostream>
#include <algorithm>
#include "cstring"
using namespace std;
typedef struct Student{
	char name[20];
	int math;
	int English;
}Student;

bool cmp(Student a, Student b){
	if(a.math > b.math){
		return a.math < b.math; //math从小到大排
	}else if(a.math == b.math{
		return a.English > b.English;
	}
}

int main(){
	Student stus[3] = {{"apple",67,89},{"limei",90,56},{"apple2",90,99}};
	//一定是到stus+3
	sort(stus, stus+3; cmp);
	for (int i = 0; i < 3; i++)
		cout << a[i].name << " " << a[i].math << " " << a[i].English << endl;
	return 0;
}

set集合: 默认从小到大,会删除重复数据

需添加头文件set;

#include <algorithm>
#include <vector>
#include <set>
int main(){
	set<int,greater<int>> m_set = { 1, 1, 5, 3, 2, 9, 6, 7, 7 }; // m_set: 9 7 6 5 3 2 1
	for (const int var : m_set)
	{
    	cout << var << " ";
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值