C ++: getting map values ​​and inserting into a second map

I have one card in one header 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 that implements another map and wants to get the first 10 parts from the map of class One.

class Two
{
  // code

  One::MapStrToInt pDataTen;

  int function1()
  {
    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 indicates that pMap:
does not have any member named "first"
does not have a member named "second"

Any suggestions?

Thanks..

+2


a source to share


4 answers


You use pointers to your maps instead of simple map objects. Thus, their indexing is similar to indexing into an array of maps. (This may be what you want, judging by your comments.)

However, first

they second

are members of an element within your map, not the map itself. Therefore, you have to iterate over the card to get the individual items and then insert them into the second card.



Now it's not entirely clear if you want to get 10 elements from the first card in your array, or 1 element from 10 cards in your array. Here's how to do it:

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);
}

      

+4


a source


pMap

is a map. You need to define an iterator to call the first, second. You can call other map API like insert, remove.



+1


a source


I suspect you can return pair<string, int>

from One::GetDetails

. Be that as it may, One

must have an array of cards (not one card!) And this method returns one of them.

0


a source


First, this function will not work:

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

      

The map is indexed by lines, not by int. The correct way to do this is to use an iterator. This is pretty 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


a source







All Articles