sort中对结构体排序的用法
程序员文章站
2022-07-12 16:32:29
...
转载自:https://blog.csdn.net/hewei0241/article/details/7545693
sort好用大家都知道的,废话不多说。
试过直接用数组,是会出现问题的,所以建议和容器一起用。
下面提供一种用法例子
-
#include <stdio.h>
-
#include <iostream>
-
#include <algorithm>
-
#include <vector>
-
using namespace std;
-
-
struct Pearls
-
{
-
int value;
-
int amount;
-
};
-
-
bool cmp(struct Pearls a, struct Pearls b)
-
{
-
if(a.value > b.value)
-
{
-
return true;
-
}
-
return false;
-
}
-
-
int main()
-
{
-
int te;
-
int i;
-
int sum;
-
int n;
-
vector<struct Pearls> a(101);
-
int max;
-
-
scanf(“%d”, &te);
-
while(te–)
-
{
-
scanf(“%d”, &n);
-
for(i = 0; i < n; i++)
-
{
-
scanf(“%d %d”, &a[i].amount, &a[i].value);
-
}
-
-
sort(a.begin(), a.end(), cmp);
-
for(i = 0; i < n; i++)
-
{
-
//printf(“%d %d\n”, a[i].amount, a[i].value);
-
}
-
max = a[0].value;
-
//printf(“%d\n”, max);
-
sum = max * (a[0].amount + 10);
-
for(i = 1; i < n; i++)
-
{
-
if(a[i].value * (a[i].amount + 10) > max * a[i].amount)
-
{
-
sum += max * a[i].amount;
-
}
-
else
-
{
-
max = a[i].value;
-
sum += max * (a[i].amount + 10);
-
}
-
}
-
printf(“%d\n”, sum);
-
}
-
//scanf(“%d”);