简体   繁体   English

使用3d数组作为C ++中地图的键?

[英]Using 3d array as key for map in C++?

Let's say I have a map using a 3d array of ints as a key, and another int as the value: 假设我有一个地图,该地图使用3d整数数组作为键,而另一个int作为值:

map<int, map<int, map<int, int> > > mp;

How do I then look through this map to check if a key exists, and then obtain the value for that key? 然后,我如何浏览此地图以检查某个键是否存在,然后获取该键的值?

I tried 我试过了

map<int, map<int, map<int, int> > >::iterator it = mp[1][3].find(4);
x = it->second;

However this gives an error. 但是,这会导致错误。 Why is this wrong? 为什么会这样呢?

EDIT: I got the error using 3d array of int, not float 编辑:我使用3d的int数组而不是浮点数得到错误

Perhaps a better structure would be with a class storing your 3d index and using it as a key ? 也许更好的结构是使用存储您的3d索引并将其用作键的类?

map<index3D, int> mp;

Then you can do something like 然后你可以做类似的事情

if(mp.count(index3D(ix, iy, iz)) > 0) // do something
// Assuming v1, v2 and v3 are int indices
if(mp.find(v1) != mp.end() &&
   mp[v1].find(v2) != mp[v1].end() &&
   mp[v1][v2].find(v3) != mp[v1][v2].end())
{
  // Key exist
  const int &value = mp[v1][v2][v3];
  ...
}
else
{
  // Key does not exis
  ...
}

You can save temporary iterators/reference and use nested loops if it performs better for you. 您可以保存临时迭代器/引用,并使用嵌套循环(如果它对您更好)。

Another simpler way to achieve same functionality is to use a std::tuple<int, int, int> or std::pair< std::pair<int, int>, int > as key. 实现相同功能的另一种简单方法是使用std::tuple<int, int, int>std::pair< std::pair<int, int>, int >作为键。 Not that both std::tuple and std::pair provide operator < . 并不是说std::tuplestd::pair提供了operator <

What is the problem with mp[1][3].find(4) mp[1][3].find(4)有什么问题

You can't apply it on cons reference. 您不能在cons参考上应用它。 If mp[1] or mp[1][3] doesn't exist, this code will unnecessary create new maps. 如果mp[1]mp[1][3]不存在,则此代码将不必要地创建新映射。

ideone example ideone的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM