The text for this exercise reads:
Write a function that given an istream and a vector<string>, produces a map<string, vector <int> > holding each string and the lines on which the string appears. Run the program on a text-file with no fewer than 1 000 lines looking for no fewer than 10 words.
This is actually quite simple. The only complicated bit is about the use of strtok, which is quite obscure. However I know of no C++ way of doing the same thing.
typedef map<string, vector<int> > line_map;
line_map count(istream& in, const vector<string>& search)
{
line_map result;
const char* tok_sep = " .,;:!-<{[()]}>/*-+\\";
char line[128];
int line_num = 0;
while (in.getline(line,127))
{
line_num++;
for (const char* word = strtok(line, tok_sep);
word;word = strtok(0, tok_sep))
{
if (find(search.begin(), search.end(), word) != search.end())
{
result[word].push_back(line_num);
}
}
}
return result;
}
The main function I wrote to test this actually had some nice stuff such as results[search[j]][k]. This is accessing the kth element in the vector returned by a map<string, vector<int> >, which in turn is being accessed using the jth element of a vector<string>.