\ When it comes to picking an associative container (like a hash map), modern C++ has a lot to offer. Sometimes, it is hard to select the most efficient dictionary data structure even for a professional engineer. Let's see what the C++23 standard library and the most prominent third-party libraries (such as boost, folly, abseil) provide, and how to pick the most suitable associative container. At the end of this series, I'll share a diagram to help you choose the best container for various purposes.
Associative container types and characteristicsThere are two major types of associative containers in C++: maps and sets. Maps allow you to store some value along with the key, and search for the value by its key. Sets only store keys but not values, and are useful when it is necessary to check if the key is present, but not retrieve the associated value. In general, all maps and sets allow adding a key to the container, erasing it, checking if some key is present, and changing the associated value for the existing key (maps only). Once the key is added to the map or set, it becomes constant and can no longer be changed.
\ Another way to categorize associative containers is key ordering. There are ordered and unordered containers. In the first category, keys are sorted according to some comparison criteria and maintain their order at all times. In unordered containers, there is no defined order to the keys, and it can change at any time.
\ Looking at the internal structure, there are node-based containers, and ones not based on separate key/key-value nodes (often called flat). Node-based ones provide stricter reference and iterator stability guarantees. Such containers often allow manipulating separate nodes (for example, moving a node from one container to another). However, node-based containers are usually less efficient than their flat counterparts.
\ Finally, containers can provide different thread safety guarantees. Most containers only allow concurrent reads when no modification happens, but some special containers provide wider capabilities.
\ Let's look at the above container categories in more detail. In this first part, I will only cover ordered containers.
Ordered containersSome containers are ordered by keys according to the comparison criteria you specify. By default, it's std::less (link), which means, keys are compared with the operator <, and are ordered from smaller to greater. This enables several extra operations, which are not available in unordered containers.
\ For example, you can search for the key which is not less than the one you provide. The following code will find the exact key if it's present in the map, or the key which would be positioned next to it in the key order.
#includeAll Rights Reserved. Copyright , Central Coast Communications, Inc.