【id:323】【10分】H. 最贵的书(输入输出重载+友元+引用)
时间限制
1s
内存限制
128MB
题目描述
定义CBook,属性包含书名(string),编者(string)、售价(double),出版社(string)。方法有:重载输入、输出。
定义友元函数find(CBook *book, int n, int &max1index,int &max2index)查找n本书中售价最高、次高的两本书,并通过引用返回其下标。若有相同售价最高、次高的两本书,按输入顺序输出第一本、第二本。
输入n,输入n本书的信息,调用上述友元函数,求价格最高的两本书下标,并按样例格式输出书信息。
输入
测试次数
每组测试数据格式如下:
n
n行书信息(书名,编者,售价,出版社)
输出
每组测试数据输出两行:
第一行:售价最高的书信息。
第二行:售价次高的书信息。
具体输出格式见样例,售价保留两位小数。书中间以空格分隔。
样例查看模式
正常显示
查看格式
输入样例1 <-复制
1
5
python从入门到精通,艾里克.马瑟斯,62.00,人民邮电出版社
Java并发编程实战,盖茨,54.5,机械工业出版社
Effective Java中文版,约书亚.布洛克,94,机械工业出版社
重构 改善既有代码的设计,马丁.福勒,122.6,人民邮电出版社
活用数据:驱动业务的数据分析实战,陈哲,61.4,电子工业出版社
输出样例1
重构 改善既有代码的设计
马丁.福勒
122.60
人民邮电出版社
Effective Java中文版
约书亚.布洛克
94.00
机械工业出版社
存在多次测试,注意格式,在不同的测试之间需要换行输出
cBooks[oneIndex].print();
cout<<endl;
cBooks[twoIndex].print();
cout<<endl;
在需要读入一行数据时,有空格时,不能使用cin>>string
需要使用 getline(cin, temp);
#include <iostream>
#include <iomanip>
using namespace std;
class CBook {
public:
//书名(string),编者(string)、售价(double),出版社(string)。方法有:重载输入、输出
string name;
string edior;
double saleMoney;
string cbs;
CBook() {}
CBook(const string &name, const string &edior, double saleMoney, const string &cbs) : name(name), edior(edior),
saleMoney(saleMoney),
cbs(cbs) {
// cout << saleMoney << endl;
}
void print() {
cout << name << endl;
cout << edior << endl;
cout << fixed << setprecision(2) << saleMoney << endl;
cout << cbs << endl;
}
friend void find(CBook *book, int n, int &max1index, int &max2index) {
double one = 0;
for (int i = 0; i < n; ++i) {
if (book[i].saleMoney > one) {
one = book[i].saleMoney;
max1index = i;
}
}
double two = 0;
for (int i = 0; i < n; ++i) {
if (book[i].saleMoney > two && i != max1index) {
two = book[i].saleMoney;
max2index = i;
}
}
}
};
int main() {
int times;
cin >> times;
while (times--) {
int number;
cin >> number;
CBook cBooks[number];
string temp;
getline(cin, temp);
for (int i = 0; i < number; ++i) {
// cin >> temp;
getline(cin, temp);
// cout << temp.size() << endl;
// cout << temp << endl;
int tempIndex = 0;
int *index = new int[3];
for (int j = 0; j < temp.size(); ++j) {
if (temp[j] == ',') {
index[tempIndex++] = j;
}
}
// cout << index[0] << endl;
// cout << index[1] << endl;
// cout << index[2] << endl;
// cout << temp.substr(0, index[0]) << endl;
// cout << temp.substr(index[0] + 1, index[1] - index[0] - 1) << endl;
// cout << temp.substr(index[1] + 1, index[2] - index[1] - 1) << endl;
// cout << temp.substr(index[2] + 1) << endl;
// cout << endl;
cBooks[i] = *new CBook(temp.substr(0, index[0]), temp.substr(index[0] + 1, index[1] - index[0] - 1),
stod(temp.substr(index[1] + 1, index[2] - index[1] - 1)), temp.substr(index[2] + 1));
}int oneIndex = 0;
int twoIndex = 0;
find(cBooks, number, oneIndex, twoIndex);
cBooks[oneIndex].print();
cout<<endl;
cBooks[twoIndex].print();
cout<<endl;
}
}