开发者

C++: retrieve map values and insert into second map

I have one map within one header file class:

class One 
{
  // code
  typedef map<string, int> MapStrToInt;

  inline MapStrToInt& GetDetails(unsigned long index)
  {
    return pData[index];
  }

  // populate pData....

private:
  MapStrToInt *pData;
};

And a second class which implements another map and wants to get the first 10 details from the class One's map.

class Two
{
  // code

  One::MapStrToInt pDataTen;

  int func开发者_开发百科tion1()
  {
    for (int i =0; i < 10; i ++)
    {
      One::MapStrToInt * pMap = &(One::GetDetails(i));
      pDataTen.insert(pair<string, int>(pMap->first,pMap->second));
    }
  }
}

When I compile this, it states that pMap:

has no member named 'first'

has no member named 'second'

Any suggestions?

Thanks..


You are using pointers to your maps, instead of plain map objects. Thus, indexing them is the same as indexing into an array of maps. (This may actually be what you want, judging from your comments.)

However, first and second are members of an element within your map, not of the map itself. So you should iterate over the map to get its individual elements, then insert them into the second map.

Now, it is not quite clear whether you want to get 10 elements from the first map in your array, or 1 element each from 10 maps in your array. Here is how to do the former:

One::MapStrToInt& map = One::GetDetails(0);
MapStrToInt::iterator it = map.begin();

for (int i =0; i < 10 && it != map.end(); i++, it++)
{
    pDataTen.insert(*it);
}


pMap is a map. You need to define iterator to call first, second. You can call other map API's like insert, remove.


I suspect that you might want to return a pair<string, int> from One::GetDetails. As it is, One must have an array of maps (not one map!), and this method returns one of those.


Firstly, this function is not going to work:

inline MapStrToInt& GetDetails(unsigned long index)
{
    return pData[index];
}

The map is indexed on strings, not ints. The correct way to do this is to use an iterator. This is fairly generic code:

map <string, int> m; 
...  // populate
map <string, int> :: iterator it = m.begin();
for ( int i = 0; i < 10; i++ ) {
   // do something with it->first and it->second
   ++it;
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜