问题
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?
回答1:
map<string, map<string, map<string, int> > > employees;
employees["person1"]["gender"]["age"] = 200;
回答2:
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;
}
};
回答3:
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;
回答4:
Nested maps?map<string, map<string, map<string, int>>> Employees;
Or make function likefindEmployee(string, string, string, int)
for it might be easier to call than dig out third level map.
回答5:
I like this approach:
std::map<std::tuple<std::string, std::string, std::string>, int> Employees;
Employees[std::make_tuple("person1", "gender", "age")] = 200;
来源:https://stackoverflow.com/questions/9288781/4d-mapping-in-c