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..
a source to share
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);
}
a source to share
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;
}