//习题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);
}
C++Primer课后题11.0、11.31
最新推荐文章于 2023-08-30 14:59:41 发布