Instead of a map<string, vector<pair<string, int> > index;
, I'd at least consider starting with a multimap<string, pair<string, int> > index;
. Both accomplish essentially the same thing: some arbitrary number of pair<string, int>
associated with one key (a string, in this case).
To display that, I'd start by overloading operator<<
for the types in the container:
// the type of the data being stored:
typedef pair<string, int> data_t;
// an overload for that:
ostream &operator<<(ostream &os, data_t> const &d) {
return os << d.first << d.second;
}
But the value_type of a map or multimap is a pair of the key and the associated data, so we need to provide an overload for that too:
ostream &operator<<(ostream &os, pair<string, data_t> const &d) {
return os << d.first << d.second;
}
Then I'd use std::copy
to copy the data to the stream:
copy(index.begin(), index.end(), ostream_iterator<data_t>(cout, "\n"));
So what'll happen is that each for each object in the map, it'll do essentially cout << object[i]
. That will print out the key and the associated data. The associated data is itself a pair<string, int>
, so that'll be printed out with the other overload of operator <<
.