For reference I found this in C++ Solutions: Companion to The C++ Programming Language by David Vandevoorde in the answer to exercise 19 in chapter 10
To output the results of the function, he used this code utilizing the copy algorithm to print the vectors out
map<string, vector<int> > *index = make_line_index(cin, entries);
vector<string>::iterator p = entries->begin();
for(; p!=entries.end(); ++p) {
cout << "Word " << *p << " appears in lines ";
map<string, vector<int> >::iterator lines = index->find(*p);
std::copy((*p).second.being(), (*p).second.end(),
ostream_iterator<int>(cout, ", "));
cout << ".\n";
}
This seems like a pretty nice way to print out a vector but my only problem with this is the output ends up with a bit of formatting ugliness that I can't seem to get rid of
example output:
Word cat appears in lines 1, 2, .
Word dog appears in lines 3, .
I was wondering if there was a simple way to fix this and still use the algorithm or would it be better to go back to using a for loop and using an if statement to make sure I don't print ", " after the last entry.
I looked into rolling back cout but it seems like thats impossible. From what I gathered seekp() doesn't work with cout.
Or if anybody has another interesting way to print out vectors I'd be happy to hear it.
If anybody wants to see the rest of Vandervoorde's solution or the exercise from Stroustrup's book I'd be happy to post it(barring any copyright problems with posting full exercises and solutions from the books). I felt like it was unnecessary to post the rest of Vandervoorde's code
Also, this is my first question on here so if I did something wrong or frowned upon don't hesitate to inform me.
Thanks