Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 922
Itzik984 Avatar asked Oct 26 '25 02:10

Itzik984


1 Answers

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;
}
like image 80
W.F. Avatar answered Oct 27 '25 18:10

W.F.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!