zoukankan      html  css  js  c++  java
  • qsort 与sort 对结构体排序实例

    qsort 与sort 对结构体排序实例

    #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;
    }
    
  • 相关阅读:
    14:求满足条件的3位数
    1696:逆波兰表达式
    筛法求素数 6分
    1751:分解因数
    1750:全排列
    1788:Pell数列
    666:放苹果
    06:寻宝
    04:最匹配的矩阵
    雷电
  • 原文地址:https://www.cnblogs.com/RioTian/p/12350603.html
Copyright © 2011-2022 走看看