4d mapping in C++?

拟墨画扇 提交于 2020-01-13 10:43:08

问题


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 like
findEmployee(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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!