Boost - unordered_set tutorial/examples/ANYTHING?
Solution 1
There's little docs on it because it behaves exactly like std::set
, with the exception that it requires a hashing and equals function instead of a comparison function. Just look up examples for std::set
, and replace them with std::unordered_set
and you should be fine.
If you need to write a hashing function, there are examples in the docs, i.e. this one.
Solution 2
Code for the most common use case:
#include <boost/unordered_set.hpp>
using boost::unordered_set;
using std::string;
using std::cout;
using std::endl;
int main (void)
{
// Initialize set
unordered_set<string> s;
s.insert("red");
s.insert("green");
s.insert("blue");
// Search for membership
if(s.find("red") != s.end())
cout << "found red" << endl;
if(s.find("purple") != s.end())
cout << "found purple" << endl;
if(s.find("blue") != s.end())
cout << "found blue" << endl;
return 0;
}
Output
found red
found blue
More Information
http://www.cplusplus.com/reference/unordered_set/unordered_set/find/
Solution 3
The boost containers are effectively an implementation of the interface first specified by the C++ Standard Library Technical Report (known as TR1), as mentioned in the boost docs. They seem to be part of the new standards working draft by now. Google turns up some more documentation/examples if you search for tr1 and unordered_set. I like the MSDN reference, which also has some samples:
http://msdn.microsoft.com/en-us/library/bb982739.aspx
http://www.google.de/search?q=tr1+unordered_set
Solution 4
I would try using the same methods of access that you use on std::set
or other containers, http://www.boost.org/doc/libs/1_37_0/doc/html/unordered.html seems to agree.
Comments
-
F. P. almost 2 years
I'd like to use
unordered_set
in a project.However, documentation for it is either incomplete or just a technical reference, no examples.
Can anyone provide links to online resources which deal with it? Books also welcome, preferably free. Google searching returned nothing of value.
Thanks!
-
John Zwinck over 13 yearsIt may have an interface very similar to std::set, but its behavior is different. Aside from the ways in which hashing makes it faster, there are also ways in which Boost's
unordered_set
can be slower, such as: svn.boost.org/trac/boost/ticket/3693 -
Billy ONeal over 13 years@John: It's performance characteristics are different, and it cannot be iterated in an ordered manner (well, it is called
unordered_set
). Otherwise it behaves exactly asstd::set
does. -
Sid almost 8 yearsThe erase performance issue has since been fixed: Quote from boost 1.61_0: Notes: In older versions this could be inefficient because it had to search through several buckets to find the position of the returned iterator. The data structure has been changed so that this is no longer the case, and the alternative erase methods have been deprecated.