我一直在解决加速 C++ 练习 8-5,我不想错过本书中的任何一个练习。
加速 C++ 练习 8-5 如下:
重新实现第 7 章中的
gen_sentence
andxref
函数以使用输出迭代器,而不是将它们的整个输出放在一个数据结构中。通过编写将输出迭代器直接附加到标准输出的程序来测试这些新版本,并将结果分别存储在list <string>
和map<string, vector<int> >
中。
为了理解这个问题的范围和本书这一部分的当前知识——这个练习是关于通用函数模板和模板中迭代器使用的章节的一部分。之前的练习是实现<algorithm>
库函数的简单版本,例如equal, find, copy, remove_copy_if
etc。
如果我理解正确,我需要修改xref
函数以便它:
- 使用输出迭代器
- 将结果存储在
map<string, vector<int> >
我试图将映射迭代器作为back_inserter()
,传递给这个函数.begin()
,.end()
但无法编译它。答案在这里解释了原因。
第 7 章中的外部参照函数:
// find all the lines that refer to each word in the input
map<string, vector<int> >
xref(istream& in,
vector<string> find_words(const string&) = split)
{
string line;
int line_number = 0;
map<string, vector<int> > ret;
// read the next line
while (getline(in, line)) {
++line_number;
// break the input line into words
vector<string> words = find_words(line);
// remember that each word occurs on the current line
for (vector<string>::const_iterator it = words.begin();
it != words.end(); ++it)
ret[*it].push_back(line_number);
}
return ret;
}
拆分实现:
vector<string> split(const string& s)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i = 0;
// invariant: we have processed characters `['original value of `i', `i)'
while (i != s.size()) {
// ignore leading blanks
// invariant: characters in range `['original `i', current `i)' are all spaces
while (i != s.size() && isspace(s[i]))
++i;
// find end of next word
string_size j = i;
// invariant: none of the characters in range `['original `j', current `j)' is a space
while (j != s.size() && !isspace(s[j]))
++j;
// if we found some nonwhitespace characters
if (i != j) {
// copy from `s' starting at `i' and taking `j' `\-' `i' chars
ret.push_back(s.substr(i, j - i));
i = j;
}
}
return ret;
}
请帮助了解我错过了什么。