题目描述
定义CBook,属性包含书名(string),编者(string)、售价(double),出版社(string)。方法有:重载输入、输出。
定义友元函数find(CBook *book, int n, int &max1index,int &max2index)查找n本书中售价最高、次高的两本书,并通过引用返回其下标。若有相同售价最高、次高的两本书,按输入顺序输出第一本、第二本。
输入n,输入n本书的信息,调用上述友元函数,求价格最高的两本书下标,并按样例格式输出书信息。
输入
测试次数
每组测试数据格式如下:
n
n行书信息(书名,编者,售价,出版社)
输出
每组测试数据输出两行:
第一行:售价最高的书信息。
第二行:售价次高的书信息。
具体输出格式见样例,售价保留两位小数。书中间以空格分隔。
//
输入样例:
1
5
python从入门到精通,艾里克.马瑟斯,62.00,人民邮电出版社
Java并发编程实战,盖茨,54.5,机械工业出版社
Effective Java中文版,约书亚.布洛克,94,机械工业出版社
重构 改善既有代码的设计,马丁.福勒,122.6,人民邮电出版社
活用数据:驱动业务的数据分析实战,陈哲,61.4,电子工业出版社
输出样例:
重构 改善既有代码的设计
马丁.福勒
122.60
人民邮电出版社
Effective Java中文版
约书亚.布洛克
94.00
机械工业出版社
AC代码:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class CBook {
public:
CBook() {}
CBook(const string& title, const string& author, double price, const string& publisher)
: title(title), author(author), price(price), publisher(publisher) {}
friend void find(CBook* book, int n, int& max1index, int& max2index);
friend istream& operator>>(istream& is, CBook& book);
friend ostream& operator<<(ostream& os, const CBook& book);
private:
string title;
string author;
double price;
string publisher;
};
void find(CBook* book, int n, int& max1index, int& max2index) {
max1index = 0;
max2index = 0;
for (int i = 1; i < n; ++i) {
if (book[i].price > book[max1index].price) {
max2index = max1index;
max1index = i;
} else if (book[i].price > book[max2index].price || max1index == max2index) {
max2index = i;
}
}
}
istream& operator>>(istream& is, CBook& book) {
string title, author, publisher;
double price;
getline(is, title, ',');
getline(is, author, ',');
is >> price;
is.ignore();
getline(is, publisher);
book = CBook(title, author, price, publisher);
return is;
}
ostream& operator<<(ostream& os, const CBook& book) {
os << book.title << endl;
os << book.author << endl;
os << fixed << setprecision(2) << book.price << endl;
os << book.publisher << endl;
return os;
}
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
cin.ignore();
CBook* books = new CBook[n];
for (int j = 0; j < n; ++j) {
cin >> books[j];
}
int max1index, max2index;
find(books, n, max1index, max2index);
cout << books[max1index] << endl;
cout << books[max2index] << endl;
delete[] books;
}
return 0;
}