nested std::map using pointers

2019-07-11 07:13发布

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

标签: c++ stl stdmap
4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-11 07:44

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';
        }
    }
}
查看更多
We Are One
3楼-- · 2019-07-11 07:48

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";
查看更多
可以哭但决不认输i
4楼-- · 2019-07-11 07:54

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

IDLL::CClass* x = (*MyMap[key1])[key2];
查看更多
走好不送
5楼-- · 2019-07-11 08:02

Try

auto outerIt = MyMap.find(someInt);
if(outerIt != MyMap.end()) {
  auto innerIt = (*outerIt)->find(someDWord);
  if(innerIt != (*outerIt)->end()) {
    auto yourElement = *innerIt;
  }
}
查看更多
登录 后发表回答