给定 N 个三元组 (x,y,z),其中 x 是整数,y 是浮点数,z 是字符串。
请你按照 x 从小到大的顺序将这些三元组打印出来。
数据保证不同三元组的 x 值互不相同。
输入格式
第一行包含整数 N。
接下来 N 行,每行包含一个整数 x,一个浮点数 y,一个字符串 z,表示一个三元组,三者之间用空格隔开。
输出格式
共 N 行,按照 x 从小到大的顺序,每行输出一个三元组。
注意,所有输入和输出的浮点数 y 均保留两位小数。
数据范围
1≤N≤10000,
1≤x,y≤105,
字符串总长度不超过 105。
输入样例:
5
32 1.36 nsyiupnnhc
18 4.53 fmofzwrah
33 4.86 wzuymbm
1 3.93 gtnrwcebt
31 4.53 gcllxioc
输出样例:
1 3.93 gtnrwcebt
18 4.53 fmofzwrah
31 4.53 gcllxioc
32 1.36 nsyiupnnhc
33 4.86 wzuymbm
注意:
①两种方法都有在结构体内重载运算符,方便进行内部的排序。
②对于一个string型的变量s,用printf输出时应当写成 “printf("%s",s.c_str());”
优先队列
#include<iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;
struct info
{
int x;
double y;
string z;
bool operator>(const info &t) const
{
return x>t.x;//小根堆重载大于号,优先成员x较小的出队
}
}mem;
priority_queue<info,vector<info>,greater<info>> pq;//小根堆
int n;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
cin>>n;
for(int i=0;i<n;i++)
{
cin>>mem.x>>mem.y>>mem.z;
pq.push(mem);
}
while(!pq.empty())
{
printf("%d %.2lf %s\n",pq.top().x,pq.top().y,pq.top().z.c_str());
pq.pop();
}
return 0;
}
不定长结构体数组
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
struct info
{
int x;
double y;
string z;
bool operator<(const info &t) const
{
return x<t.x;//重载小于号,对结构体数组按照成员x从小到大排序
}
}mem;
vector<info> ans;
int n;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
cin>>n;
for(int i=0;i<n;i++)
{
cin>>mem.x>>mem.y>>mem.z;//先赋值给一个中间变量
ans.push_back(mem);//再将中间变量插进mem数组
}
sort(ans.begin(),ans.end());//排序操作
for(auto t:ans)
printf("%d %.2lf %s\n",t.x,t.y,t.z.c_str());
return 0;
}