练习11.27:
如果要在multimap中统计关键字出现的个数,则使用count,如果要在map中查询指定关键字是否出现,则使用find
练习11.28:
#include <iostream>
using namespace std;
#include <map>
#include <string>
#include <set>
#include <vector>
int main()
{
map<string, vector<int>>mp = { {"hello",{12,13,14,15,16}},{"world",{26,27,28,39,30}},{"c++",{91,92,93,94,95} } };
//用来保存find返回结果的变量
map<string, vector<int>>::iterator find_it = mp.find("world");
cout << find_it->first << ": ";
for (const auto& c : find_it->second)
{
cout << c << " ";
}
cout << endl;
system("pause");
return 0;
}
练习11.29:
如果给定关键字不在容器中,
upper_bound返回指向给定关键字的插入位置迭代器,这个插入位置能保持容器中的元素位置
lower_bound返回指向给定关键字的插入位置迭代器,这个插入位置能保持容器中的元素位置
equal_range返回一个保存迭代器对的pair,pair中的两个迭代器都指向给定关键字可以插入的位置
练习11.30:
pos是一个pair类型的数据,保存了两个迭代器,分别指向给定关键字元素的第一个位置和最后一个元素之后的位置,pos->first指向第一个位置迭代器,解引用后得到一个pair<string,string>类型的数据,再调用second成员就可以访问关键字对应的元素值
练习11.31:
#include <iostream>
using namespace std;
#include <map>
#include <string>
#include <set>
#include <vector>
int main()
{
multimap<string, string>authors = {
{"Alain de Botton","China"},{"Alain de Botton","fuck"},
{"Alain de Botton","Yes"},
{"haha dea yotton","666"},{"haha dea yotton","hello"},
{"haha dea yotton","No speaking" }
};
cout << "删除元素前:" << endl;
for (auto c : authors)
{
cout << c.first << ": " << c.second << endl;
}
string search_item("Alain de Botton");
//删除的方法有好几种,题目要求使用find
//找到该关键字对应的元素数量
size_t entries = authors.count(search_item);
//找到第一个该关键字对应的元素
map<string, string>::iterator iter = authors.find(search_item);
//如果容器中没有这个关键字,entries为0,不执行while中的删除操作
while (entries)
{
iter = authors.erase(iter);
--entries;
}
cout << "删除元素后:" << endl;
for (auto c : authors)
{
cout << c.first << ": " << c.second << endl;
}
system("pause");
return 0;
}
练习11.32:
在multimap中关键字是按字典序排序的,但关键字对应的元素值有多个,且他们并没有按字典序排序,为了实现关键字对应的元素值也能按字典序排序,将原数据存入map<string, set<string>>中在进行打印
#include <iostream>
using namespace std;
#include <map>
#include <string>
#include <set>
#include <vector>
int main()
{
multimap<string, string>authors = {
{"Alain de Botton","anthor"},{"Alain de Botton","fuck"},
{"Alain de Botton","button"},
{"haha dea yotton","something"},{"haha dea yotton","hello"},
{"haha dea yotton","no speaking" },{"bob","simth"},
{"bob","how life"},{"gaga","happy man"}
};
//元素值排序前
cout << "元素值排序前: " << endl;
for (auto c : authors)
{
cout << c.first << ": " << c.second << endl;
}
//为了实现关键字对应的元素值也能按字典序排序,将原数据存入map<string, set<string>>中在进行打印
map<string, set<string>>printOrder;
for (auto c : authors)
{
printOrder[c.first].insert(c.second);
}
cout << endl;
cout << endl;
cout << endl;
//打印
//元素值排序后
cout << "元素值排序后: " << endl;
for (auto c : printOrder)
{
cout << c.first << ": ";
for (auto s : c.second)
{
cout << "\""<<s<<"\"" << " ";
}
cout << endl;
}
system("pause");
return 0;
}