<algorithm.h>中sort对结构体排序的用法

sort好用大家都知道的,废话不多说。

试过直接用数组,是会出现问题的,所以建议和容器一起用。

下面提供一种用法例子

 

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #include <iostream>  
  3. #include <algorithm>  
  4. #include <vector>  
  5. using namespace std;  
  6.   
  7. struct Pearls  
  8. {  
  9.     int value;  
  10.     int amount;  
  11. };  
  12.   
  13. bool cmp(struct Pearls a, struct Pearls b)  
  14. {  
  15.     if(a.value > b.value)  
  16.     {  
  17.         return true;  
  18.     }  
  19.     return false;  
  20. }  
  21.   
  22. int main()  
  23. {  
  24.     int te;  
  25.     int i;  
  26.     int sum;  
  27.     int n;  
  28.     vector<struct Pearls> a(101);  
  29.     int max;  
  30.       
  31.     scanf("%d", &te);  
  32.     while(te--)  
  33.     {  
  34.         scanf("%d", &n);  
  35.         for(i = 0; i < n; i++)  
  36.         {  
  37.             scanf("%d %d", &a[i].amount, &a[i].value);  
  38.         }  
  39.           
  40.         sort(a.begin(), a.end(), cmp);  
  41.         for(i = 0; i < n; i++)  
  42.         {  
  43.             //printf("%d %d\n", a[i].amount, a[i].value);  
  44.         }  
  45.         max = a[0].value;  
  46.         //printf("%d\n", max);  
  47.         sum = max * (a[0].amount + 10);  
  48.         for(i = 1; i < n; i++)  
  49.         {  
  50.             if(a[i].value * (a[i].amount + 10) > max * a[i].amount)  
  51.             {  
  52.                 sum += max * a[i].amount;  
  53.             }  
  54.             else  
  55.             {  
  56.                 max = a[i].value;  
  57.                 sum += max * (a[i].amount + 10);  
  58.             }  
  59.         }  
  60.         printf("%d\n", sum);  
  61.     }  
  62.     //scanf("%d");  
  63. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值