2018.10.30——十一章关联容器-11.1使用关联容器 11.2关联容器概述

11.1
关键字值与元素数据建立对应关系,这就是“关联”的含义
11.2
11.3
答案

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

using namespace std;

int main(int argc, char *argv[])
{
	ifstream in(argv[1]);
	if (!in)
	{
		cerr << "无法打开文件" <<endl;
		exit(1);
	}
	
	map<string, size_t> words_count;
	set<string> exclude = {
	string word;
	while(in>>word)
	if(
		++words_count(word);
	
	for (auto &w : words_count)
		cout << w.first << " 出现了 " << w.second <<"次" << endl;
	return 0;
}

11.4
答案
关键的转换函数

string &trans(string &s)
{	
	for (int i= 0; i< s.size() ; ++i)
	{
		if (s[i] <= 'Z' && s[i] >= 'A')
			s[i] -= ('A' - 'a');
		else if(s[i] == ',' || s[i] == '.')
			s[i] = s.erase(i, 1);
	}
	return s;
}

11.5
11.7
答案

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

using namespace std;

void add_family(map<string,vector<string>> &families , const string &family)
{
	if (find(families.begin(), families.end(), family) == families.end())
		families[family] = vector<string> ();
}

void add_child(map<string,vector<string>> &families , const string &family, const string &child)
{
	families[family].push_back(child);
}

int main(int argc, char *argv[])
{
	map<string,vector<string>> families;

	add_family(families,"张");
	add_child(families,"张","强");

	for (auto &f : families)
	{
		cout << f.first << "家的孩子:" ;
		for(auto &c : f.second)
			cout << c << " ";
		cout << endl;
	}
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值