11.27 当需要统计容器中有多少元素的关键字与给定关键字相同,使用count;当无需统计个数,只关心关键字是否在容器中时,用find。
11.28 map<string, vector<int>> m; map<string, vector<int>>::iterator iter; find返回一个迭代器,指向具有给定关键字的元素。
11.29 如果给定关键字不在容器中,lower_bound和upper_bound会返回相等的迭代器,指向一个不影响排序的关键字的插入位置;equal的两个迭代器都指向关键字可以插入的位置。
11.30 pos.first是指向第一个与关键字匹配的元素,pos.first->second得到该元素的值,也就是作者第一部著作的题目。
11.31
#include <iostream>
#include <map>
using namespace std;
void remove_author(multimap<string, string> &books, const string &author)
{
auto entries = books.count(author);
if (!entries) {
cout << "author doesn't exist" << endl;
return;
} else {
auto iter = books.find(author);
while (entries) {
iter = books.erase(iter);
--entries;
}
}
}
void print_books(multimap<string, string> &books)
{
if (books.empty()) {
cout << "It's empty" << endl;
return;
}
for (auto item : books) {
cout << "author: " << item.first << "; "
<< item.second << endl;
}
}
int main()
{
multimap<string, string> books;
books.insert({"author1", "book11"});
books.insert({"author1", "book12"});
books.insert({"author2", "book21"});
books.insert({"author2", "book22"});
cout << "before erase: " << endl;
print_books(books);
remove_author(books, "author1");
cout << "after remove author1: " << endl;
print_books(books);
remove_author(books, "author3");
cout << "after remove author3: " << endl;
print_books(books);
return 0;
}
11.32 见上一题的print_books函数
11.33
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <map>
using namespace std;
map<string, string> buildMap(ifstream &map_file)
{
map<string, string> trans_map;
string key, value;
while (map_file >> key && getline(map_file, value)) {
if (value.size() > 1)
trans_map[key] = value.substr(1);
else
throw runtime_error("no rule for " + key);
}
return trans_map;
}
const string &transform(const string &s, const map<string, string> &m)
{
auto map_it = m.find(s);
if (map_it != m.cend())
return map_it->second;
else
return s;
}
void word_transform(ifstream &map_file, ifstream &input)
{
auto trans_map = buildMap(map_file);
string text;
while (getline(input, text)) {
istringstream stream(text);
string word;
bool firstword = true;
while (stream >> word) {
if (firstword)
firstword = false;
else
cout << " ";
cout << transform(word, trans_map);
}
cout << endl;
}
}
int main(int argc, char *argv[])
{
ifstream map_file(argv[1]);
ifstream text(argv[2]);
word_transform(map_file, text);
return 0;
}
11.34 将find替换为下标,如果关键字不存在,会用值初始化的方式构造一个pair插入到容器中。
11.35 当关键字不在map中,使用insert和使用下标没有区别;当关键字在map中时,使用下标会用新值覆盖原有值,而insert会返回一个值指出插入失败。
11.36 buildMap函数会使用value.size()检查单词是否存在,如果不存在,则抛出一个异常。