简体   繁体   中英

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM