c++ qsort 与sort 对结构体排序 c++ qsort 与sort 对结构体排序实例代码

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

c++ qsort 与sort 对结构体排序 c++ qsort 与sort 对结构体排序实例代码

RioTian   2021-01-28 我要评论
#include<bits/stdc++.h>
using namespace std;
 
typedef struct {
	string book;
	int num;
}Book;
 
//qsort的比较函数
int cmp(const void * a, const void * b) {
	return (*(Book*)a).num > (*(Book*)b).num ? 1 : 0;
}
 
//sort的比较函数
bool cmp_(Book a, Book b) {
	return a.num > b.num;
}
 
 
int main() {
	Book Bok[3] = { {"1",4},{"2",2},{"3",3} };
 
 
	cout << endl << "----------------" << "qsort函数" << endl;
	qsort(Bok, 3, sizeof(Bok[0]),cmp);
 
	for (auto i : Bok) {
		cout << i.num << endl;
	}
 
	cout << "----------------" << "sort函数" << endl;
	sort(Bok, Bok + 3, cmp_);
 
	for (auto i : Bok) {
		cout << i.num << endl;
	}
 
	return 0;
}

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们