Game Development Reference
In-Depth Information
Chapter 16
STL's Associative Containers
All of the STL containers you have seen so far have stored individual data elements. In this chapter
you will be introduced to associative containers. These containers associate a key with the data
values that you are inserting. In the case of the map and unordered_map containers, you are required
to supply a value to use as the key, whereas the set and unordered_set containers automatically
generate keys from the data you supply. I'll explain the differences between each of these containers
as I work through some examples in this chapter, beginningwith the set container.
The STL set Container
You won't be surprised to find out that a set is a template class and you are required to specialize
the set container to store the types you require. Listing 16-1 gives an example of how you can
specialize the set template.
Listing 16-1. Specializing set
using namespace std;
using MySet = set<int>;
Once you have specialized a set template you can initialize a container in the same manner as other
STL containers. Listing 16-2 shows how you can create and add values to a set .
Listing 16-2. Initializing and Adding to set Containers
MySet mySet = { 2, 1, 0 };
mySet.emplace(4);
mySet.insert(3);
There are two important aspects of Listing 16-2 to which you should pay particular attention. The first is
the emplace method used. This method has the same result as the insert method in that the value will be
added to the set . However, emplace is actually faster at achieving this than insert in some circumstances.
It achieves this speed improvement by avoiding a copy construction when using a set with class types.
You should always use emplace rather than insert with all containers when it is available.
169
 
Search WWH ::




Custom Search