C++Primer11.4节练习

练习11.37:

无序容器不用关注关键字的顺序,不需要去维护元素的序,比较简单,在关键字类型的元素没有明显的序关系的情况下,无序容器更有用

有序容器在对关键字顺序有要求的情况下,性能更好

练习11.38:

重写单词计数程序:基本没区别,将map换为unordered_ma即可

#include <iostream>
using namespace std;
#include <map>
#include <string>
#include <set>
#include <unordered_map>

int main()
{
	unordered_map<string, size_t>word_count;

	string word;
	int i = 10;
	//输入十对单词-计数器对
	while (i != 0 && cin >> word)
	{
		++word_count[word];
		--i;
	}
	for (const auto& w : word_count)
	{
		cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times " : " time") << endl;
	}
	system("pause");
	return 0;
}

重写单词转换程序:将map换为unordered_ma即可

#include <iostream>
using namespace std;
#include <map>
#include <unordered_map>
#include <string>
#include <set>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>

const string& transform(const string& s, unordered_map<string, string>& mp_trans)
{
	auto it = mp_trans.find(s);
	if (it != mp_trans.end())
	{
		//在单词转换规则中,转换后返回
		return it->second;
	}
	else
	{
		//没有在单词转换规则中,s不变
		return s;
	}
}

unordered_map<string, string> buildMap(ifstream& ifst_trans)
{
	unordered_map<string, string>trans_map;
	string value, key, trans_value;
	while (ifst_trans >> key && getline(ifst_trans, value))
	{
		//这里value.size() > 1是geiline除了读入空格还读入了其他
		if (value.size() > 1)
		{
			trans_value = value.substr(1);
			trans_map.insert(pair<string, string>(key, trans_value));
		}
		else
		{
			throw runtime_error("no rule for " + key);
		}
	}
	return trans_map;

}

void word_transform(ifstream& ifst_trans, ifstream& ifst_input)
{
	auto trans_map = buildMap(ifst_trans);
	string text;
	//按行读取打印
	while (getline(ifst_input, text))
	{
		istringstream istr(text);
		string word;
		bool firstword = true;
		//每一个单词结束后需要打印空格
		while (istr >> word)
		{
			if (firstword)
			{
				firstword = false;
			}
			else
			{
				cout << " ";
			}

			cout << transform(word, trans_map);
		}
		cout << endl;
	}
}

int main()
{
	ifstream ifst_trans("regular.txt");
	ifstream ifst_input("transform.txt");
	word_transform(ifst_trans, ifst_input);
	system("pause");
	return 0;
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白学C++.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值