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?
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;
}
};
map<string, map<string, map<string, int> > > employees;
employees["person1"]["gender"]["age"] = 200;
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With