【发布时间】:2015-06-19 12:59:33
【问题描述】:
在我的编程课上,我们开始从 C 转到 C++,我们当前的实验任务是创建一个程序,它给定一个文本文件读取其内容,然后返回文件中的单词列表以及行它们出现的数量以及该单词在每行中出现的次数,格式为 Word Line:Count。
Foo bar bar
Baz
Foo
<EOF>
应该返回:
Foo 1:1 3:1
Bar 1:2
Baz 2:1
到目前为止,我们讨论的唯一数据结构是地图,我们使用地图编写了以下输出总字数的程序
int main(int argc, const char*argv[]) {
map<string, unsigned int> table;
string word;
while (cin >> word) {
++table[word];
}
for (std::map<string, unsigned int>::iterator itr = table.begin();
itr != table.end(); ++itr) {
cout << itr->first << "\t" << itr->second << endl;
}
return 0;
}
我们被告知可以(稍微)最低限度地修改这个程序,以便让它打印出行号和字数。我的问题是,有没有办法使用地图为每个键设置 2 个值?或者有没有更好的方法来实现这样的东西?
【问题讨论】:
-
1) 您必须将输入代码修改为 notice 行号,然后再担心如何存储它们,2) 每个键有 2 个值是困难的并且不足以回答,但 3)这里有一个很大的提示:而不是
map<string, int>,想想map<string, map<int, int>>。
标签: c++ dictionary word-count line-numbers