0

如何显示这张名为索引的地图的内容?

map< string, vector< pair<string, int> > > index

我制作了一个迭代器,并使用以下代码在地图的开头制作了它:

map< string, vector< pair<string, int> > >::iterator it;
it = index.begin(); 

...我使用这个 for 循环来显示地图内容,但它给了我错误:

for ( it =index.begin() ; it != index.end(); it++ )
    cout << (*it).first <<(*it).second <<endl;

我知道错误是(*it).second因为它指的是向量,但我无法解决这个问题。

4

2 回答 2

0

(*it).second has no meaning by itself in this context. You need to use the vector public interface to extract data (see it in vector documentation) from it or do whatever manipulation that you need.

于 2012-12-15T18:44:40.937 回答
0

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 <<.

于 2012-12-15T18:45:29.177 回答