vector的综合案例(书籍作者 问题)

问题:已知作者的基本信息有作者的编号、姓名,书籍信息有书号、书名、出版社,一位作者可以出版许多书,最后并打印出作者及其出版的书的信息,用集合类来展示上述关系。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>
using namespace std;

class Book
{
public:
    Book(const string &id, const string &name, const string &bpublic) :
        b_id(id), b_name(name), b_public(bpublic){}
public:
    string b_id;
    string b_name;
    string b_public;
};

class BookShow
{
public:
    void operator()(const Book &b)
    {
        cout << b.b_id << "\t" << b.b_name << "\t" << b.b_public << endl;
    }
};

class Writer
{
public:
    Writer(const string &id, const string &name):w_id(id), w_name(name){};
    void AddBook(const Book &book)
    {
        m_books.push_back(book);
    }
    friend ostream &operator<<(ostream &os, const Writer &w);
private:
    string w_id;
    string w_name;
    vector<Book> m_books;
};

ostream &operator<<(ostream &os, const Writer &w)
{
    os << w.w_id << w.w_name << endl;
    for_each(w.m_books.begin(), w.m_books.end(), BookShow());
    return os;
}

class WriterCollect
{
public:
    void AddWriter(const Writer &writer)
    {
        vw.push_back(writer);
    }

    void showWriterInfo()
    {
    	cout << "作者及其书籍的信息如下:" << endl;
        copy(vw.begin(), vw.end(), ostream_iterator<Writer>(cout, "\n"));
    }

private:
    vector<Writer> vw;
};

int main()
{
    Writer w1("1001", "zhangsan");
    Book b1("b001", "aaa", "public");
    Book b2("b002", "bbb", "public");
    w1.AddBook(b1); w1.AddBook(b2);

    Writer w2("1002", "lisi");
    Book b3("b003", "ccc", "public");
    w2.AddBook(b3);

    WriterCollect wc;
    wc.AddWriter(w1);
    wc.AddWriter(w2);

    wc.showWriterInfo();

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值