I am stuck in solving C ++ 8-5 Accelerated Exercises, and I don't want to miss one exercise in this book.
Accelerated Exercise 8-5 C ++ is as follows:
Repeat the gen_sentence and xref functions from chapter 7 to use output iterators instead of putting all their result in the same data composition. Check out these new versions by writing programs that attach the output of the iterator directly to standard output, and also save leads to list <string> and map<string, vector<int> > respectively.
To understand the scope of this question and current knowledge in this part of the book, this exercise is part of a chapter on common function templates and the use of an iterator in templates. The previous exercise was to implement simple versions of <algorithm> library functions such as equal, find, copy, remove_copy_if , etc.
If I understand correctly, I need to change the xref function so that it:
- Use output iterator
- Save results
map<string, vector<int> >
I tried passing the map iterator as back_inserter() , .begin() , .end() this function, but I could not compile it. The answer here explains why.
xref, as in chapter 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; }
Split implementation:
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; }
Please help me understand what I am missing.