Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

4d mapping in C++?

Tags:

c++

visual-c++

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?

like image 310
Justin k Avatar asked Feb 15 '12 06:02

Justin k


3 Answers

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;
    }
};
like image 80
Jerry Coffin Avatar answered Oct 31 '22 14:10

Jerry Coffin


map<string, map<string, map<string, int> > > employees;
employees["person1"]["gender"]["age"] = 200;
like image 24
Mohammad Dehghan Avatar answered Oct 31 '22 16:10

Mohammad Dehghan


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;
like image 22
tpg2114 Avatar answered Oct 31 '22 16:10

tpg2114