Itzik984
Itzik984

Reputation: 16794

Unordered_map using pointer address as key

I'm trying to create a map with a custom key, which is an object's pointer address, as mentioned.

I need the address because for now it's the only relevant way to compare between two objects.

from what i understood, the proper way of doing this is by using const char* as key

here is the typedef :

typedef __gnu_cxx::unordered_map<const char*, std::string> TargetsTags;

I'm a bit confused about the following:

how do I create the operator() ?

This is what i used for std::string:

namespace __gnu_cxx {
    template<>
    struct hash<std::string>
    {
        hash<const char*> h;
        size_t operator()(const std::string &s) const
        {
            return h(s.c_str());
        };
    };
}

What about const char*?

And is this the correct way of doing this?

Upvotes: 4

Views: 6698

Answers (1)

W.F.
W.F.

Reputation: 13988

The working example using c++11:

#include <iostream>
#include <unordered_map>
#include <string>
#include <functional>

using namespace std;

class myhash {
public:
   size_t operator() (const char *val) const {
      return std::hash<std::string>()(val);
   }
};

class myequal {
public:
   bool operator()(const char *val1, const char *val2) const{
      return std::string(val1) == std::string(val2);
   }
};



int main() {

   std::unordered_map<const char*, string, myhash, myequal> mymap;
   mymap["abc"] = "abcd";
   mymap["cba"] = "dcba";
   std::cout << mymap["abc"] << std::endl;
   return 0;
}

Upvotes: 5

Related Questions