#include<iostream>
#include<string>
#include<sstream>
#include<iomanip>
using namespace std;
class CBook {
private:
string name, writer;
double price;
string publish;
public:
CBook() { price = 0; }
CBook(string name, string writer, double price, string publish) :name(name), writer(writer), price(price), publish(publish) {}
friend void find(CBook* book, int n, int& max1index, int& max2index);
friend istream& operator>>(istream& stream, CBook& book);
friend ostream& operator<<(ostream& stream, CBook& book);
bool operator>(const CBook& a) {
if (price > a.price) {
return true;
}
return false;
}
};
istream& operator>>(istream& stream, CBook& book) {
string line;
getline(stream, line);
stringstream ss(line);
string tmpN, tmpW, tmpP;
double tmpPrice;
getline(ss, tmpN, ',');
getline(ss, tmpW, ',');
ss >> tmpPrice;
ss.ignore();
getline(ss, tmpP, ',');
book.name = tmpN;
book.writer = tmpW;
book.price = tmpPrice;
book.publish = tmpP;
return stream;
}
ostream& operator<<(ostream& stream, CBook& book) {
cout << book.name << endl;
cout << book.writer << endl;
cout <<fixed<<setprecision(2)<< book.price << endl;
cout << book.publish << endl;
cout << endl;
return stream;
}
void find(CBook* book, int n, int& max1index, int& max2index) {
//找最大
CBook tmp;
for (int i = 0; i < n; i++) {
if (book[i] > tmp) {
max1index = i;
tmp = book[i];
}
}
//找次大
CBook tmp2;
for (int i = 0; i < n; i++) {
if (i == max1index)
continue;
if (book[i] > tmp2) {
max2index = i;
tmp2 = book[i];
}
}
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
CBook* book = new CBook[n];
for (int i = 0; i < n; i++) {
cin >> book[i];
}
int max1;
int max2;
find(book, n, max1, max2);
cout << book[max1];
cout << book[max2];
delete[]book;
}
return 0;
}id:323】【10分】D. 最贵的书(输入输出重载+友元+引用)
时间限制
1s
内存限制
128MB
题目描述
定义CBook,属性包含书名(string),编者(string)、售价(double),出版社(string)。方法有:重载输入、输出。
定义友元函数find(CBook *book, int n, int &max1index,int &max2index)查找n本书中售价最高、次高的两本书,并通过引用返回其下标。若有相同售价最高、次高的两本书,按输入顺序输出第一本、第二本。
输入n,输入n本书的信息,调用上述友元函数,求价格最高的两本书下标,并按样例格式输出书信息。
输入
测试次数
每组测试数据格式如下:
n
n行书信息(书名,编者,售价,出版社)
输出
每组测试数据输出两行:
第一行:售价最高的书信息。
第二行:售价次高的书信息。
具体输出格式见样例,售价保留两位小数。书中间以空格分隔。
IO模式
本题IO模式为标准输入/输出(Standard IO),你需要从标准输入流中读入数据,并将答案输出至标准输出流中。
样例查看模式
正常显示
查看格式
输入样例1 <-复制
1
5
python从入门到精通,艾里克.马瑟斯,62.00,人民邮电出版社
Java并发编程实战,盖茨,54.5,机械工业出版社
Effective Java中文版,约书亚.布洛克,94,机械工业出版社
重构 改善既有代码的设计,马丁.福勒,122.6,人民邮电出版社
活用数据:驱动业务的数据分析实战,陈哲,61.4,电子工业出版社
输出样例1
重构 改善既有代码的设计
马丁.福勒
122.60
人民邮电出版社
Effective Java中文版
约书亚.布洛克
94.00
机械工业出版社
该代码显示部分正确,请在保证源代码基本不变的情况下分析查找哪里出错了