练习11.27 对于什么问题你会使用count来解决?什么时候你又会选择find呢?
需要统计元素的个数使用count,否则使用find。
练习11.28对一个string到int的vector的map,定义并初始化一个变量来保存在其上调用find所返回的结果。
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
int main()
{
vector<int> p_num{ 3,34 };
vector<int> j_num{ 23,13,1 };
map<string, vector<int>> player_num{ {"Paul", p_num},{"Janmes",j_num} };
map<string, vector<int>>::iterator iter = player_num.find("Paul");
cout << iter->first << ": ";
for (auto &i : iter->second) {
cout << i << " ";
}
}
练习11.29 如果给定的关键字不在容器中,upper_bound、lower_bound和equal_range分别会返回什么?
upper_bound和lower_bound返回一个相同的迭代器,指向一个不影响排序关键字插入位置。
equal_range返回一对迭代器。指向相同的位置,一个不影响排序关键字插入的位置。
练习11.30 对于本节最后一个程序中的输出表达式,解释运算对象pos.first->second的含义。
pos是一对迭代器,指向的元素的范围。
pos.first是指向元素第一次出现的迭代器。
pos.first->second 指向该元素。
练习11.31编写程序,定义一个作者及其作品的multimap。使用find在multimap中查找一个元素并用erase删除它。确保你的程序在元素不在map中也能正常运行。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
multimap<string, string> authors{ {"LuXun","aQ"}, {"LuXun","riji"} ,{"C++primer","Lippman"} };
string author;
cin >> author;
auto iter = authors.find(author);
if (iter != authors.end()) {
authors.erase(author);
}
for (auto &i : authors) {
cout << i.first << " " << i.second << endl;
}
}
练习11.32 使用上一题定义的multimap编写一个程序,按字典顺序打印作者列表和他们的作品。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
multimap<string, string> authors{ { "LuXun","aQ" },{ "LuXun","riji" } ,{ "C++primer","Lippman" } };
string author,text;
while (cin >> author >> text) {
authors.insert({ author,text });
}
for (auto beg = authors.begin(); beg != authors.end(); ++beg) {
cout << beg->first << " " << beg->second << endl;
}
}