2

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

4 Answers 4

2

Try

auto outerIt = MyMap.find(someInt);
if(outerIt != MyMap.end()) {
  auto innerIt = (*outerIt)->find(someDWord);
  if(innerIt != (*outerIt)->end()) {
    auto yourElement = *innerIt;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you are sure the keys exist, you could also try:

IDLL::CClass* x = (*MyMap[key1])[key2];

Comments

1

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

Comments

0

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";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.