11.4节练习

练习11.37 一个无序容器与其有序版本相比有何优势?有序版本有何优势?

无序容器性能优秀。

有序容器可以按<运算符处理元素。


练习11.38 用unordered_map重写单词计数程序(参见11.1节,第375页)和单词转换程序(参见11.3.6节,第391页)。

//单词统计程序
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <string>
using namespace std;
int main()
{
	unordered_map<string, size_t> word_count;
	unordered_set<string> exclude = { "the","an","a","and","or" };
	string word;
	while (cin >> word) {
		if (exclude.find(word) == exclude.cend()) {
			++word_count[word];
		}
	}
	for (auto &i : word_count) {
		cout << i.first << " occurs " << i.second << (i.second > 1 ? "times" : "time") << endl;

	}
	return 0;

}
//单词转换程序。
#include <iostream>
#include <string>
#include <unordered_map>
#include <fstream>
#include <sstream>
using namespace std;
void main_func(ifstream &, ifstream&);
unordered_map<string, string> build_map(ifstream&);
const string &transform(const string &, unordered_map<string, string> &);
int main()
{
	ifstream map_file("map_file.txt");
	ifstream input("input.txt");
	main_func(map_file,input);
}
void main_func(ifstream &map_file, ifstream&input)
{
	auto trans_unordermap = build_map(map_file);
	string line;
	while (getline(input, line)) {
		istringstream stream(line);
		string word;
		bool firstword = true;
		while (stream >> word) {
			if (firstword == true) {
				firstword = false;
			}
			else
			{
				cout << " ";
			}
			cout << transform(word, trans_unordermap);
		}
		cout << endl;
	}
}
unordered_map<string, string> build_map(ifstream &map_file)
{
	unordered_map<string, string>change_rule;
	string key;
	string mapped;
	while (map_file >> key && getline(map_file, mapped)) {
		if (mapped.size() > 1) {
			change_rule[key] = mapped.substr(1);
		}
		else {
			throw runtime_error("no data for change " + key);
		}
	}
	return change_rule;
}
const string &transform(const string &s, unordered_map<string, string>&m)
{
	auto iter = m.find(s);
	if (iter != m.cend()) {
		return iter->second;
	}
	else {
		return s;
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值