<algorithm.h>中sort对结构体排序的用法
2016-01-25 21:33
603 查看
sort好用大家都知道的,废话不多说。
试过直接用数组,是会出现问题的,所以建议和容器一起用。
下面提供一种用法例子
[cpp] view
plain copy
#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");
}
试过直接用数组,是会出现问题的,所以建议和容器一起用。
下面提供一种用法例子
[cpp] view
plain copy
#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");
}
相关文章推荐
- 网页设计和网页开发人员常用到的Google Chrome扩展
- django 三天写个人博客
- golang使用protobuf
- GMS(Google Mobile Service)预制方法
- libgo 2.0发布
- 交叉编译 google protobuf
- 十大高明的Google搜索技巧
- 十大高明的Google搜索技巧
- 交叉编译 google protobuf
- goagent使用步骤
- goldengate ERROR OGG-01172
- go get安装第三方包的前提条件和步骤
- golang环境搭建
- mongo_2 $in 和 $all 区别
- Django学习之路
- DWG数据添加到GoogleEarth上显示步…
- 如何在DJANGO里获取?带数据的东东,基于CBV
- kernel开机logo总结
- Google数据交换格式:ProtoBuf
- google 浏览器非应用商店扩展程序安装