In this article, we’ll take a look at using the unordered map data structure in C++.

This is a part of the C++ Standard Template Library (STL), and is a very useful data structure.

Let’s look at this in more detail, using some illustrative examples.

The Unordered Map Data Structure

This is an associative container that can store elements as a key-value pair.

Here, you associate a key with a mapped value. We can access this mapped value through this key.

The advantage of using this data structure is due to it’s very fast insertion and deletion time (O(1) time complexity on average).

Since an unordered map uses a Hash Table, this will directly provide us with very fast access times!

Let’s now understand this, using some illustrative examples.

Using an unordered map in C++ STL

This is a part of the STL in C++, defined at <unordered_map>.

#include <unordered_map>

template <class Key, class Value> class unordered_map;

The most common arguments are Key and Value, which is the key-value pair.

There are other arguments which you can pass to std::unordered_map, but for the sake of illustration, we won’t be using them. (You can refer to them here)

Let’s get started now!

Unordered Map in C++ STL – Some Examples

Let’s look at some examples of the unordered map in C++.

1. Inserting to an Unordered Map

Let’s first declare our container structure, by assigning it to a variable.

#include <iostream>
#include <unordered_map>
#include <string>

int main() {
    // We declare our unordered map (int, string)
    // Here, the key is an int, and the value is a string
    std::unordered_map<int, std::string> my_map;

    // Direct array-like access!
    my_map[10] = "Hello from JournalDev!";
    my_map[20] = "Sample String";

    std::cout << my_map[10] << std::endl;
    std::cout << my_map[20] << std::endl;

    return 0;
}

Notice the similarities between this and the array, with the same way of assigning and accessing!

Output

Hello from JournalDev!
Sample String

It looks very easy to assign and modify using array-like indexing. Now, we’ll look at iterating through an unordered map.

By definition, since an unordered map does not define any order, we cannot guarantee that the elements are printed in order.

Remember that this is a Hash Table. Due to that, the values will be inserted at a random position, based on it’s hash value.

#c++ #programming-c #cplusplus

Understanding the unordered map in C++
2.75 GEEK