问题
I am using a map inside a map and want to access a specific member in the second map.
std::map<int, std::map<DWORD,IDLL::CClass*>*> MyMap
回答1:
Try
auto outerIt = MyMap.find(someInt);
if(outerIt != MyMap.end()) {
auto innerIt = (*outerIt)->find(someDWord);
if(innerIt != (*outerIt)->end()) {
auto yourElement = *innerIt;
}
}
回答2:
If you are sure the keys exist, you could also try:
IDLL::CClass* x = (*MyMap[key1])[key2];
回答3:
You can use std::map::find
in two steps: first to find the value associated with the key in the outer map, and then repeat for the inner map.
The following compilable code seems to work with VS2010 SP1 (VC10):
#include <iostream>
#include <map>
typedef unsigned int DWORD;
namespace IDLL
{
struct CClass
{
CClass() : n(0) {}
explicit CClass(int nn) : n(nn) {}
int n;
};
} // namespace IDLL
int main()
{
//
// Prepare maps for testing
//
std::map<int, std::map<DWORD,IDLL::CClass*>*> MyMap;
IDLL::CClass c1(10);
IDLL::CClass c2(20);
std::map<DWORD, IDLL::CClass*> m1;
m1[10] = &c1;
m1[20] = &c2;
MyMap[30] = &m1;
//
// Testing code for maps access
//
const int keyOuter = 30;
auto itOuter = MyMap.find(keyOuter);
if (itOuter != MyMap.end())
{
// Key present in outer map.
// Repeat find in inner map.
auto innerMapPtr = itOuter->second;
const DWORD keyInner = 20;
auto itInner = innerMapPtr->find(keyInner);
if (itInner != innerMapPtr->end())
{
IDLL::CClass * classPtr = itInner->second;
std::cout << classPtr->n << '\n';
}
}
}
回答4:
If you aren't sure the keys exist:
std::map<DWORD,IDLL::CClass*>* inner = MyMap[key1];
IDLL::CClass* x = 0;
if(inner)
x = (*inner)[key2];
if(x)
std::cout << "Winner! " << *x << "\n";
else
std::cout << "Loser.\n";
来源:https://stackoverflow.com/questions/15363505/nested-stdmap-using-pointers