C++Primer课后题11.0、11.31

//习题11.9
string &trans(string &s)
{
    for (int p = 0; p < s.size(); p++) {
        if (s[p] > 'A' && s[p] < 'Z')
            s[p] -= ('A' - 'a');
        else if (s[p] == ',' || s[p] == '.' || s[p] == ',')
            s.erase(p, 1);
    }
    return s;
}
int main()
{
    ifstream in("data.txt");
    if (!in) {
        cerr << "打开文件失败" << endl;
        return -1;
    }
    map<string, list<int>> word_linenum;
    string line, word;
    int linenum = 0;
    while (getline(in, line)) {
        linenum++;
        istringstream l_in(line); //istringstream 从string中读取数据,ifstream从文件中读取string
        while (l_in >> word) {
            trans(word);
            word_linenum[word].push_back(linenum);
        }
    }
    for (const auto &w : word_linenum) {
        cout << w.first;
        for(auto i: w.second)
            cout << " " << i;
        cout << endl;
    }
}

//习题11.31
// 定义一个作者及其作品的multimap ,find erase,

void remove_author(multimap<string, string> &books, const string &author)
{
    auto book_num = books.count(author);
    if (!book_num) {
        cerr << "书目中没有作者:" << author << endl;
    }
    while(book_num--)
        books.erase(books.find(author)++);
}
void print_books(multimap<string, string> &books)
{
    cout << "当前书目:" << endl;
    for (auto &book : books)
        cout << book.first << "---- <<" << book.second << ">>" << endl;
}
int main()
{
    multimap<string, string> books;
    books.insert({ "王小波" ,"黄金时代" });
    books.insert({ "王小波" ,"似水流年" });
    books.insert({ "贾平凹" ,"古炉" });
    books.insert({ "贾平凹" ,"废都" });
    books.insert({ "刘震云" ,"1942" });
    books.insert({ "奥威尔" ,"1984" });
    print_books(books);
    remove_author(books, "贾平凹");
    print_books(books);
    remove_author(books, "贾平凹");
    print_books(books);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值