One of the advantages of associate containers is that they have a very fast search feature. This is accomplished by the fact that they store data in a binary tree. The downside of this is that there is no index value to the containers making it more challenging to loop through an entire data set.
So how do we do this in C++? We use an iterator. An iterator is an object in C++ that is designed to keep track of a position as you loop through the data. Since associative data containers do not have an index number, the iterator points to the position as you loop through the set.
In C++, iterators are part of the standing library and do not require a separate import statement, however they need to be defined relative to the data set that they are iterating through. Notice below that we define the iterator type and then give it a variable name, in this case it
.
Once declared, we then need to give the iterator a starting position. While iterators can start anywhere, to loop through an entire set, we usually set the iterator to start at the beginning using the .begin()
command.
An iterator is actually a pointer that is pointing to a specific value that is currently being referenced. As a result, to get the actual value, we need to use the dereferencing operator, *
.
Let’s take a look at this in an example.
Notice in the example above that the beginning place for the iterator is not the first value inserted into the set. Sets and maps store values in a binary tree for quick access. With this in mind, it is important to note that the iterator beginning can change anytime you add or delete values, so it will need to be reset.
Using the iterator and an incrementor, we can now loop through all the values in a data set. Both a while loop and a for loop will work, but one thing that looks a little different is the ending point. In a normal for loop, we typically loop while the variable is less than a particular value. We loop with an iterator while the iterator does not equal the end value.
Let’s take a look at an example.
Notice above how we increment the iterator using the normal incriminator operator, it ++
. We can also count by two or other increments similar to how we would with other for loops.
Iterating through a map is done in the exact same way as a set, but the one difference we have is that there is a key and a value. The iterator points to each key/value pair and we can then access it by referencing the first
value for the key and second
value for the value.
Here is an example using a while loop.
Now it is your turn to try it. Given the set below, try creating an iterator and looping through the values to print them all out.