Requirements for elements in std::unordered_set
Asked Answered
C

1

10
std::unordered_set<my_type> my_set;

Which requirements must my_type fulfill here? (Besides a specialization for std::hash)

Chaffee answered 29/3, 2012 at 14:17 Comment(1)
You can just look this up in n3337 [unord.req] 23.2.5. Find n3337 on this page.Fionnula
E
10

You need a specialization for std::hash, and you need an operator == defined to handle hash collisions.

EDIT: You should also make sure your type has a copy constructor (or let the compiler generate one for you) because STL containers have value semantics.

EDIT2: as an example of how to do this, you can check out this other SO answer.

Exsect answered 29/3, 2012 at 14:20 Comment(10)
What about move/copy constructors and assignment operators?Chaffee
Yeah you'll probably need those too. But more directly, the type must be hashable and equality comparable.Exsect
So move doesn't do the job? (I kind of hoped it would, since vector etc. go fine with it..)Chaffee
Moving would do the job if you are moving the object into the container. However, moving isn't a requirement because if the object cannot be moved, but can still be copied, then you can use it in the container.Exsect
I meant no copy but only move. ;)Chaffee
Oh! Well it looks like unordered_set has an insert( ) overload for rvalues. So moving instead of copying should be okay. Test it!Exsect
Well, I could've tested it before, I'm asking here to be sure it is compliant.Chaffee
@Chaffee : If your type is not copyable then the std::unordered_set<> instance will also not be copyable. I.e., move-only is fine as long as you're okay with the std::unordered_set<> instance also being move-only.Lamm
-1: "You should also make sure your type has a copy constructor" C++11 containers are moveable as well. And containers don't have to be copyable; they're only copyable if the contents are copyable.Debi
Also -1: Exactly which of move constructor, copy constructor, move assignment, and copy assignment are needed are exactly what I was looking for!Conceal

© 2022 - 2024 — McMap. All rights reserved.