Indrojit Mondal
Indrojit Mondal

Reputation: 11

How can I assign values to a map < map<int,int> , bool >?

How can I assign values to a map declaring like this?

map < map<int,int> , bool > Map;

I want code to look like this:

Map[u][v]=true;

Where u or v can be maximum 10^5.

How can I code this?

Upvotes: 0

Views: 473

Answers (2)

doug
doug

Reputation: 4299

If there is no need for the ordering behavior of map as @WhozCraig noted in a comment then unordered_map is a much faster choice.

std::unordered_map<int, std::unordered_map<int, bool> > myMap;

However, wrapping a single unordered_map with a helper class will typically halve the execution time since only one hash needs to be done to look up the two integers.

class Map2ints
{
    class Map2Helper {
        int u;
        std::unordered_map<int64_t, bool> &vmap;
    public:
        bool& operator[](int v) { return vmap[u | (static_cast<int64_t>(v) << 32)]; }
        Map2Helper(int u, std::unordered_map<int64_t, bool> &vmap) :u(u), vmap(vmap) {}
    };
    std::unordered_map<int64_t, bool> vmap;
    bool contains(int u, int v) { return vmap.find(u | (static_cast<int64_t>(v) << 32))!=vmap.end(); }
public:
    Map2Helper operator[](int u) { return Map2Helper{ u, vmap }; }
};

Then the usage would be the same. For instance:

Map2ints myMap;
myMap[70000][151] = true;
bool a = myMap[70000][151];  // which sets a to true

Upvotes: 0

Tim Johnsen
Tim Johnsen

Reputation: 180

what you want is:

std::map<int, std::map<int, bool> > myMap;

Then you can set/get values by:

bool myBool;
myMap[u][v] = myBool;
myBool = myMap[u][v];

Upvotes: 4

Related Questions