11.3.5节练习

练习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;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值