我有一个3D地图容器,声明如下:
std::map<std::string, std::map<std::string, std::map<std::string, CGridItem*> > > m_3DGridItems;假设我有一个CGridItem对象指针值,如何有效地获取所有三个映射键字符串?谢谢!
发布于 2011-10-05 17:47:38
首先,你真的需要这样一个笨拙的容器吗?
拥有一个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* (因此您不必自己同步两个结构)。
发布于 2011-10-05 16:08:34
您可以只使用迭代器来获取映射中的所有键/值。当值也是一个映射时,您可以通过相同的方式获取键/值...
发布于 2011-10-05 16:09:13
第一件事:如果你主要做这样的查找,这种数据结构肯定是而不是是性能最好的替代方案。
除了嵌套三个for循环之外,我看不到任何其他方法,因为map的布局是按键而不是按值进行查找的。它看起来像这样:
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 libraries中可用。
https://stackoverflow.com/questions/7658288
复制相似问题