0

Suppose I have a custom string like type:

struct MyType {
  std::string str_;
  int somethingElse;
}

Now, I know how to make it usuable in a std::set - just supply < operator.

How can I use it with a std::unordered_set ? when it is supposed to be based on the std::string str_ member ?

std::unordered_set<MyType> um;

Update: I have already seen this answer: C++ unordered_map using a custom class type as the key It looks somewhat outdated(c++11 ?) and also concerns map

darune
  • 10,480
  • 2
  • 24
  • 62
  • Any reason why you want to use `std::unordered_set` instead of `std:unordered_map` ? – Yksisarvinen Jun 18 '19 at 12:26
  • The answer is exactly the same for `std::unordered_set`. And it didn't change between C++11 and C++17. – Yksisarvinen Jun 18 '19 at 12:41
  • @Yksisarvinen hmmm, really, i have to specialize within the std namespace ? – darune Jun 18 '19 at 12:56
  • 2
    Adding template specializations for `std::hash` is the only (known to me) exception in standard, when you are allowed to add something to `namespace std`. But you can provide your hash functor as template argument for `std::unordered_set` as well, which is nicer IMO. And given that your hash function will be just returning hash of `std::string`, I'd rather go for `std::unordered_map` – Yksisarvinen Jun 18 '19 at 13:02
  • @Yksisarvinen normally a good idea, but I simply can't make the map work with actual code. – darune Jun 18 '19 at 13:06
  • 1
    You have to either provide a `std::hash` or use `std::unordered_set` as the type where `MyHasher` acts like `std::hash` would. – Ben Jun 19 '19 at 16:49

0 Answers0