11.1节练习

练习11.1 描述map和vector的不同。

map的关键字可以是string类型 而vector只能按整型下标索引。

map有映射的作用,可存放更多数据。


练习11.2 分别给出最适合使用list vector deque map 以及set的例子。

list:排名作为下标查成绩,发现作弊者,从链表中删除。

vector :排名作为下标查对象,第一名湖人队,第二名凯尔特人队...

deque :排队,进一个出一个。

map; 以人名映射电话号码 地址。

set:将特定的某一类对象放一起,如世界500强企业的名字。


练习11.3 编写你自己的单词计数程序。

#include <iostream>
#include <string>
#include <map>
#include <set>
using namespace std;
int main()
{
	map<string, size_t> word_count;
	set<string> exclude{ "a","an","the","or","and" };
	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;
}


练习11.4 扩展你的程序,忽略大小写和标点。例如,“example.”、“example,”Example“应该递增相同的计数器。

#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
	map<string, size_t> word_count;
	set<string> exclude{ "a","an","the","or","and" };
	string word;
	while (cin >> word) {
		// remove_if....这该死的算法在通用型迭代器中并没有真的删除元素
		auto iter = remove_if(word.begin(), word.end(),ispunct);
		word.erase(iter, word.end());
		for (auto &s : word) {
			s = tolower(s);
		}
		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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值