如何从给定的3D地图值获得所有的键
How to get all keys from a given 3D map value?
我有一个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库中可用。
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 无法将结构注册为增强几何体3D点
- 基于多个条件处理地图中的所有元素
- 在C++中将矢量转换为嵌套地图
- OpenGL大的3D纹理(>2GB)非常慢
- 是什么导致了Unity 3D中的"错误线程异常"?
- 替换基于地图的所有引用
- 如何区分地图中的 0 和 false?
- 地图计数确实很重要,或者只是检查是否存在
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 如何从地图中删除矢量对象
- 是否有任何C++功能可以对地图进行排序?
- 如何使用 std::variant 打印地图键/值?
- 有没有办法从点云和深度数据构建和存储3D地图
- 开放世界 3D 环境的最佳地图格式
- 除非同时构造,否则无法在 3D 地图中分配值
- 我应该使用地图、3D 数组还是坚持使用堆栈
- 如何从给定的3D地图值获得所有的键
- 插入和读取值从3D地图
- 在3D地图中插入值