6

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 4d mapping.

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

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

Justin k
  • 1,104
  • 5
  • 22
  • 33

5 Answers5

6

You normally want to combine all three parts of the key into a single class, with a single comparison operator. You could either use something like a pair<pair<string, string>, string>, or a boost::tuple, or define it yourself:

class key_type { 
    std::string field1, field2, field3;
public:
    bool operator<(key_type const &other) { 
        if (field1 < other.field1)
            return true;
        if (field1 > other.field1)
            return false;
        if (field2 < other.field2)
            return true;
        if (field2 > other.field2)
            return false;
        return field3 < other.field3;
    }
};
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
5
map<string, map<string, map<string, int> > > employees;
employees["person1"]["gender"]["age"] = 200;
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
2

You can use std::pair as your keys instead.

For example,

typedef std::pair<std::string, std::string> key_part;
typedef std::pair<key_part, std::string> key;
std::map<key, int> Employees;

Which could then be used like:

key_part partialKey = std::pair<std::string, std::string>("person1","gender");
key myKey = std::pair<key_part, std::string>(partialKey, "age");
Employees[myKey] = 200;
tpg2114
  • 14,112
  • 6
  • 42
  • 57
1

Nested maps?
map<string, map<string, map<string, int>>> Employees;

Or make function like
findEmployee(string, string, string, int)
for it might be easier to call than dig out third level map.

alxx
  • 9,897
  • 4
  • 26
  • 41
1

I like this approach:

std::map<std::tuple<std::string, std::string, std::string>, int> Employees;
Employees[std::make_tuple("person1", "gender", "age")] = 200;
Akira Takahashi
  • 2,912
  • 22
  • 107