我有一个3D地图容器,声明如下:
std::map<std::string, std::map<std::string, std::map<std::string, CGridItem*> > > m_3DGridItems;假设我有一个CGridItem对象指针值,如何有效地获取所有三个映射键字符串?谢谢!
发布于 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
复制相似问题