最贵的书(输入输出重载+友元+引用)

题目描述

定义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;
}

  • 31
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

szuzhan.gy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值