第十一章 11.2.2节练习

练习11.9

定义一个map,将单词与一个行号的list关联,list中保存的单词所出现的行号。

解答:

#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
#include <cctype>
#include <list>

using namespace std;

int main(){
	map<string, list<int>> word_to_lines;
	ifstream fin("test.txt");
	string line, word;
	size_t line_num(0);

	while (getline(fin, line)){
		++line_num;
		if (line == ""){
			continue;
		}
		istringstream iss(line);
		while (iss >> word){
			for (size_t i = 0; i < word.size(); ++i){
				word.at(i) = tolower(word.at(i));
			}
			if (word.size() && !isalpha(word.front())){
				word.erase(word.begin());
			}
			if (word.size() && !isalpha(word.back())){
				word.erase(word.begin() + (word.size() - 1));
			}
			if (word != ""){
				word_to_lines[word].push_back(line_num);
			}
		}
	}

	for (auto iter = word_to_lines.begin(); iter != word_to_lines.end(); ++iter){
		cout << iter->first << " appeared on ";
		for (auto i : iter->second){
			cout << i << " ";
		}
		cout << "line(s)."<< endl;
	}

	return 0;
}
这里使用了之前11.4练习的程序,不过这个程序还是有问题,当单词不以空格分隔的时候,分析就会出错。

这里,我们使用固定格式的文本作为测试,暂不去处理分隔的问题。


练习11.10

可以定义一个vector<int>::iterator到int的map吗?

list<int>::iterator到int的map呢?

对于两种情况,如果不能,解释为什么。

解答:

	map<vector<int>::iterator, int> vec_to_int;
	map<list<int>::iterator, int> list_to_int;
看了下英文原版,感觉翻译没什么问题。但是,的确我不大清楚这道题想要表达什么意思。

如果只是定义类似如上的map,那么完全没有问题。(不过这种问题,一般都是“不能”的回答,需要对其原因进行解释)

(PS,解答请看评论)


练习11.11

不是用decltype重新定义bookstore。

解答:

multiset<Sales_data, bool(*)(const Salse_data&, const Salse_data&)>
使用函数指针替换decltype定义。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值