Game Development Reference
In-Depth Information
Hash maps achieve this by turning the key into a hash value and then using that hash to store the
data in an appropriate bucket. The process of writing a hash map is a complicated task, but luckily
for us the STL provides us with two ready-made hash map containers, the unordered_set and the
unordered_map .
STL unordered_set and unordered_map
The code for unordered_set and unordered_map is going to look very familiar. Listing 16-8 shows
how you can specialize these templates.
Listing 16-8. Specializing unordered_set and unordered_map
using namespace std;
using MyUnorderedSet = unordered_set<int>;
using MyUnorderedMap = unordered_map<int, string>;
using MyPair = pair<int, string>;
The unordered_set and unordered_map container templates take the same parameters as the set
and map containers. The unordered_set stores a value and calculates the key automatically for the
value,whereas the unordered_map requires that you specify the type to use for the key followed by
the type for the value.
You can then initialize and add elements to these containers in the same way you did before,
as Listing 16-9 shows.
Listing 16-9. Initializing and Adding to unordered_set and unordered_map
MyUnorderedSet myUnorderedSet = { 2, 1, 0 };
myUnorderedSet.emplace(4);
myUnorderedSet.insert(3);
MyUnorderedMap myUnorderedMap = { { 2, "Two" }, { 1, "One" }, { 0, "Zero" } };
myUnorderedMap.emplace(3, "Three");
MyPair node{ 4, "Four" };
myUnorderedMap.insert(node);
The code to find elements in an unordered_set is similar to what you have seen previously, either
using the find algorithm or the find method. Listing 16-10 shows both versions.
Listing 16-10. Using find with unordered_set
MyUnorderedSet::iterator found = find(myUnorderedSet.begin(), myUnorderedSet.end(), 2);
if (found != myUnorderedSet.end())
{
cout << "Found : " << *found << endl;
}
found = myUnorderedSet.find(2);
if (found != myUnorderedSet.end())
{
cout << "Found : " << *found << endl;
}
 
Search WWH ::




Custom Search