C++Primer第五版 习题答案 第十一章关联容器

11.1

map是关联式容器,元素式按关键字保存和访问的;
vector是顺序容器,其元素是按照它在容器中的位置来保存和访问的;

11.2

list:插入较多情况;
vector:动态数组;
deque:需要头部和尾部增删的情况;
map:字典;
set:添加忽略关键字;

11.3

#include<iostream>
#include<string>
#include<map>

using namespace std;

int main() {
   
	map<string, size_t> word_count;
	string words;
	while (cin>>words)
	{
   
		++word_count[words];
	}
	for (const auto &s : word_count)
		cout << s.first << " occurs  " << s.second << ((s.second > 1) ? " times " : " time ") << endl;
	return 0;
}

11.4

#include<iostream>
#include<string>
#include<map>
#include<algorithm>
#include<set>

using namespace std;

int main() {
   
	map<string, size_t> word_count;
	set<string>exclude{
    "you","i" };
	string words;
	
	while (cin>>words)
	{
   
		words.erase(find_if(words.begin(), words.end(), ::ispunct), words.end()); //删除单词后面的标点
		for_each(words.begin(), words.end(), [](char& c) {
   c = tolower(c); }); //单词转换为小写
		if(exclude.find(words)==exclude.end()) //忽略部分单词
			++word_count[words];
	}
	for (const auto &s : word_count)
		cout << s.first << " occurs  " << s.second << ((s.second > 1) ? " times " : " time ") << endl;
	return 0;
}


11.5

set中只有关键字;
map包括关键字-值对;

11.6

set关联式容器,查找较快;
list顺序容器,查找关键字与容器的大小有关;

11.7

#include<iostream>
#include<string>
#include<map>
#include<vector>

using namespace std;

int main() {
   
	map<string, vector<string>>	family;
	string first_name, last_name;
	cin >> last_name;
	while (cin >> first_name)
	{
   
		family[last_name].push_back(first_name);
	}
	for (const auto f : family) {
   
		cout << f.first << endl;
		for (const auto s : f.second)
			cout << s << " ";
		cout << endl;
	}
	return 0;
}

11.8

效率更高,不用遍历判断重复;

#include<iostream>
#include<string>
#include<vector>

using namespace std;

int main() {
   
	vector<string>vs;
	string s;
	while (cin >>s)
	{
   
		if (find(vs.begin(), vs.end(), s) == vs.end())
			vs.push_back(s);
	}
	for (const auto s : vs)
		cout << s << " ";
	cout << endl;
	return 0;
}

11.9

map<string,list<size_t>> words_line;

11.10

对于有序容器必须定义元素的比较方法,默认<;
vector<int>::iterator 可以,因为定义了<;
list<int>::iterator不可以,未定义<;

11.11

#include <set>
#include 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值