解题方法
使用结构体存储数据,重写std::cin
和std::cout
并使用std::sort
来完成题目要求。
C++代码
#include <iostream>
#include <iomanip> // std::setprecision()
#include <string>
#include <algorithm>
struct tuple
{
int x;
float y;
std::string z;
tuple(int x, float y, std::string z)
: x(x), y(y), z(z)
{}
tuple()
:x(0), y(0.0),z("")
{}
friend std::istream& operator>>(std::istream& is, tuple& t);
friend std::ostream& operator<<(std::ostream& output, const tuple& t);
};
std::istream& operator>>(std::istream& input, tuple& t)
{
input >> t.x >> t.y >> t.z;
return input;
}
std::ostream& operator<<(std::ostream& output, const tuple& t)
{
output << t.x << " " << std::fixed << std::setprecision(2) << t.y << " " << t.z;
return output;
}
int main()
{
int cnt = 0;
std::cin >> cnt;
tuple* tps = new tuple[cnt];
for (int i = 0; i < cnt; i++)
std::cin >> tps[i];
std::sort(tps, tps + cnt, [](const tuple& lhs, const tuple& rhs) { return lhs.x < rhs.x; });
for (int i = 0; i < cnt; i++)
std::cout << tps[i] << "\n";
delete[] tps;
}