2011-10-05 43 views
0

我有3D地图容器声明如下:如何从给定的3D地图值中获取所有按键?

std::map<std::string, std::map<std::string, std::map<std::string, CGridItem*> > > m_3DGridItems; 

假设我有一个CGridItem对象指针的值,我怎么能得到一个有效的方式,所有的三种地图钥匙串?谢谢!

+0

是的。我用三个笨拙的循环来做到这一点。任何简单明了的方法? – GoldenLee

回答

0

您可以使用迭代器来获取地图中的所有键/值。当这个值也是一个地图的时候,你可以用同样的方法得到这个键/值...

0

第一件事:如果你主要是做这样的查找,这个数据结构肯定是不是最好表演替代品。

除了制作三个嵌套for循环,我没有看到任何其他方式,因为地图是按键进行查找的,而不是按值进行查找。这将是这个样子:

std::map<std::string, std::map<std::string, std::map<std::string, CGridItem*> > >:iterator it1; 
CGridItem* obj = ...; 
for(it1 = mymap.begin(); it != mymap.end(); ++it1) 
{ 
    std::map<std::string, std::map<std::string, CGridItem*> > it2; 
    for(it2 = it1->second.begin(); it2 != it->second.end(); ++it2) 
    { 
     std::map<std::string, CGridItem*> it3; 
     for(it3 = it2->second.begin(); it3 != it2->second.end(); ++it3) 
     { 
      if(it3->second == obj) { 
       /*found it!*/ 
       /* your 3 strings are in it1->first, it2->first, it3->first */ 
      } 
     } 
    } 
} 

编辑:我提出以下数据结构:

std::map<CGridItem*, std::tuple<std::string, std::string, std::string> > mymap; 

这是你CGridItem对象映射到3串。注意:当您不使用C++ 11时,std::tuple可能不可用,但在boost libraries中可用。

+0

Constantinius:谢谢!我想我必须像这样定义另一个3D地图:std :: map >> myAnotheMap; – GoldenLee

+0

如何使用不同的数据结构?我会更新我的答案,只需一秒钟。 – Constantinius

+0

另外不要忘记,最初他可以为不同的字符串元组使用相同的'CGridItem',如果您在新数据结构中反转键值关系,则不再可能。 – Grozz

2

首先,你真的需要这样一个笨拙的容器吗?

这将是更容易有Key结构:

struct Key { 
    std::string x; 
    std::string y; 
    std::string z; 
}; 

然后定义上Key排序:

bool operator<(Key const& left, Key const& right) { 
    if (left.x < right.x) { return true; } 
    if (left.x > right.x) { return false; } 

    if (left.y < right.y) { return true; } 
    if (left.y > right.y) { return false; } 

    return left.z < right.z; 
} 

然后你就可以有一个更容易的结构来操纵:

std::map<Key, GridItem*> 

如果您需要映射两种方式,ch eck out Boost.Bimap它保持双向映射Key <-> GridItem*(所以你不必自己同步两个结构)。

相关问题