如何从给定的3D地图值获得所有的键

How to get all keys from a given 3D map value?

本文关键字:3D 地图      更新时间:2023-10-16

我有一个3D地图容器声明如下:

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

假设我有一个CGridItem对象指针值,我怎么能得到所有三个映射键字符串在一个有效的方式?谢谢你!

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

有一个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*>

如果您需要以两种方式映射,请查看Boost。Bimap,它维护一个双向映射Key <-> GridItem*(所以你不需要同步两个结构自己)。

您可以使用迭代器来获取映射中的所有键/值。当值也是映射时,您可以以同样的方式获取键/值…

首先,如果您主要是进行这样的查找,那么这个数据结构绝对不是最佳性能选择。

我认为除了创建三个嵌套的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 */
            }
        }
    }
}

EDIT:我提出如下的数据结构:

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

这将您的CGridItem对象映射到3个字符串。注意:当您不使用c++11时,std::tuple可能不可用,但它在boost库中可用。