user5739619
user5739619

Reputation: 1838

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:

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

Upvotes: 0

Views: 226

Answers (2)

Mohit Jain
Mohit Jain

Reputation: 30489

// 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. Not that both std::tuple and std::pair provide operator <.

What is the problem with mp[1][3].find(4)

You can't apply it on cons reference. If mp[1] or mp[1][3] doesn't exist, this code will unnecessary create new maps.

ideone example

Upvotes: 1

steiner
steiner

Reputation: 170

Perhaps a better structure would be with a class storing your 3d index and using it as a key ?

map<index3D, int> mp;

Then you can do something like

if(mp.count(index3D(ix, iy, iz)) > 0) // do something

Upvotes: 3

Related Questions