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

2022-07-27,,,,

#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;
}

以上就是c++ qsort 与sort 对结构排序实例代码的详细内容,更多关于c++ qsort 与sort 对结构体排序的资料请关注其它相关文章!

《c++ qsort 与sort 对结构体排序实例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。