Problem Source - Accelerated C ++, Problem 8-5
I wrote a small program that examines the input lines of a line and counts the number of times a word appears on a given line. The following code does the following:
#include <map>
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <cctype>
#include <iterator>
using std::vector; using std::string;
using std::cin; using std::cout;
using std::endl; using std::getline;
using std::istream; using std::string;
using std::list; using std::map;
using std::isspace; using std::ostream_iterator;
using std::allocator;
inline void keep_window_open()
{
cin.clear();
cout << "Please enter EOF to exit\n";
char ch;
cin >> ch;
return;
}
template <class Out>
void split(const string& s, Out os)
{
vector<string> ret;
typedef string::size_type string_size;
string_size i = 0;
while (i != s.size()) {
while (i != s.size() && isspace(s[i]))
++i;
string_size j = i;
while (j != s.size() && !isspace(s[j]))
++j;
if (i != j) {
*os++ = (s.substr(i, j - i));
i = j;
}
}
}
map<string, vector<int> > xref(istream& in)
{
string line;
int line_number = 0;
map<string, vector<int> > ret;
while (getline(in, line)) {
++line_number;
vector<string> words;
split(line, back_inserter(words));
for (vector<string>::const_iterator it = words.begin();
it != words.end(); ++it)
ret[*it].push_back(line_number);
}
return ret;
}
int main()
{
cout << endl << "Enter lines of text, followed by EOF (^Z):" << endl;
map<string, vector<int> > ret = xref(cin);
for (map<string, vector<int> >::const_iterator it = ret.begin();
it != ret.end(); ++it) {
cout << it->first << " occurs on line(s): ";
vector<int>::const_iterator line_it = it->second.begin();
cout << *line_it;
++line_it;
while (line_it != it->second.end()) {
cout << ", " << *line_it;
++line_it;
}
cout << endl;
}
keep_window_open();
return 0;
}
As you can see, the split function is a template function for handling various types of output iterators as desired.
My problem arises when I try to generalize the xref function by passing the templated split function as an argument. I don't seem to believe the type is correct.
, : , , ? , ?
, , xref , ( ). LINE 2 LINE 3 uncomment LINE 4, find_words ( split.)
!