7

Can you please tell me how I can write multidimensional map. For two dimensional map, I did the following:

map<string, int> Employees
Employees[“person1”] = 200;

I was trying to use something similar to following for 3d mapping.

map<string, string, int> Employees;
Employees[“person1”, “age”] = 200;

Can you please tell me the correct way to do this?

and Is there a way I can initialize all the map elements to be 0 ? Just like on a array we can say int array[10]={0};

Learner_51
  • 1,075
  • 3
  • 22
  • 38

4 Answers4

9

You need to create map of maps like that.

map<string, map<string, int> > employees;
employees["person1"]["age"] = 200;
Boris Strandjev
  • 46,145
  • 15
  • 108
  • 135
  • Is there a way I can initialize all the map function to be 0 ? Just like on a array we can say `int array[10]={0};` – Learner_51 Feb 12 '12 at 10:25
  • The call to map[key] initializes the object with the type default constructor. For integer this is exactly zero. This means that for any two randomly chosen keys `emplyees["foo"]["bar"] == 0` will return true. – Boris Strandjev Feb 12 '12 at 10:27
  • Ok, I should have tried it out first. Thanks for all the help. – Learner_51 Feb 12 '12 at 10:29
6

You can use the pair class of the utility library to combine two objects:

map<pair<string, string>, int> Employees;
Employees[make_pair("person1", "age")] = 200;

See http://www.cplusplus.com/reference/std/utility/pair/

Eser Aygün
  • 7,794
  • 1
  • 20
  • 30
3

Instead of nested map, you can use tuple as keys; (this is a c++11 code, you could do the same with boost::tuple as well).

#include<map>
#include<tuple>
#include<string>
using namespace std;
map<tuple<string,string>,int> m;
int main(){
    m[make_tuple("person1","age")]=33;
}
eudoxos
  • 18,545
  • 10
  • 61
  • 110
0

what you are doing here is not 3D mapping but 2D mapping, how to use stl::map as two dimension array

Correct 3D mapping will be like

map<string, map<string, map<int, string> > > Employees;
Employees[“person1”][“age”][20] = "26/10/2014";
Community
  • 1
  • 1
Ritwik
  • 521
  • 7
  • 17