Page cover

πŸ“–STL in CPP ( Part II)

STANDARD TEMPLATE LIBRARY II - MAPS - 2023

Standard Template Library (STL) II - Associative Containers

A map is an ordered sequence of pairs (key, value) in which we can look up a value based on a key. Data structures similar to map are associative arrays, hash tables, and red-black trees.

Associative Containers

  1. map an ordered container of (key,value) pairs

  2. set an ordered container of keys

  3. unordered_map an unordered container of (key,value) pairs

  4. unordered_set an unordered container of keys

  5. multimap a map where a key can occur multiple times

  6. multiset a set where a key can occur multiple times

  7. unordered_multimap a unordered_map where a key can occur multiple times

  8. unordered_multiset a unordered_set where a key can occur multiple times

Maps

What is a map? The map class template looks like this:

std::map<Key, Data, Compare, Alloc>

STP map implementations are more like a balanced binary search trees (BST). To be more specific, they are red-black trees.

red-black

A tree is built up from nodes. A node holds a key, its corresponding value, and pointers to two descendants' nodes. We won't go into details, but one thing we should remember is that the red-black tree has guaranteed log(n) height tree.

Let's look at the simple code which shows how to use maps.

The template for the map defined inside namespace std is:

the first template argument is the type of the element's key, and the second template argument is the type of the element's value.

When we define:

Let's look at the sample program counting the number of words in the input file.

To use a map, we must include the header file <map>

Output from the run is:

The elements of a map may have any types of key and value that meet the following two requirements:

  1. The key/value pair must be assignable and copyable.

  2. The key must be comparable with the sorting criterion.

In the code:

we are inserting a key/value pair in three different ways:

  1. Use pair<> Use pair<> directly.

  2. Use value_type To avoid implicit type conversion, we pass the correct type explicitly by using value_type, which is provided as a type definition by the container type.

  1. Use make_pair The most convenient way is to use make_pair function. This function produces a pair object that contains the two values passed as arguments:

Then when we tried to erase the element at the end, we used '--' operator on the iterator end() because it is pointing to the one passed the end element.

Reading in data to fill a map

The following example reads in string data from a file and fills in vector.

The std::istreamstd::ctype_base::space is the default delimiter which makes it stop reading further character from the source when it sees whitespace or newline.

As we can see from the data file (names) we're using:

as an input. When we reads in the data, it stores first_name and last name into the vector. But we want to treat them as a pair. So, we later put the pair into a map.

Here is the code:

Output:

Note that we're using C++11 auto keyword that can deduce the type from context, we should let the compiler know we want the file compiled with C++11:

Efficiency - add vs update

In his book "Effective STL", Scott Meyers talked about the efficiency of map::operator[] and map::insert. He recommends using map::insert for adding and map::operator[] for updates.

Maps for Word Count

Following code counts the word using maps. It first reads in the Stairway To Heaven Lyrics (Led Zeppelin), then put it into a map<string,int>. The first string argument is the word and the second argument is the counter which shows how many times the key appeared in the lyric.

Output should look like this:

To extract a word from a string, we use several separators (delimiters) as in the line:

It include space, tab, '.', and ';'.

Then we find the beginning and end of the word in between the delimiters:

Then we assign the word extracted to a string "str" while incrementing the count:

Hash Table vs. STL map

Compare a hash table vs. an STL map How we implement hash table? Instead of hash table, what data structure options can be used for the case when the number of input is small?

  1. Hash Table

    1. A value is stored by applying hash function on a key. So, values are not stored in sorted order.

    2. Because hash table uses the key to find the index that will store the value, an insert/loopkup can be done in O(1) time if we can assume there are only a few collisions in the hash table.

    3. Potential collisions should be handled properly.

  2. STL map

    1. Insertion of key/value is in sorted order of key.

    2. It uses a tree to store values - O(logN) insert/lookup.

    3. No need to handle collisions.

    4. An STL map works well to:

      1. find min/max element

      2. print elements in sorted order

      3. find the exact element or if the element is not found, find the next smallest number.

So, how a hash table implemented?

  1. A good hash function is needed to ensure that the hash values are uniformly distributed.

  2. A collision protection method is required:

    1. chaining - for dense table entries.

    2. probing - sparse table entries.

  3. Implement methods to dynamically increase or decrease the hash table size on a given criterion.

When the number of inputs is small, we can use STL map as an option for data structure. Since N is small, O(logN) is negligible.

Multimap example - Anagrams from a dictionary

In this code, we assume we have a dictionary (dict), and get anagrams from it. Each character represents a prime number. We match the smallest prime number with the most frequent alphabet so that the products of characters of a word can be smaller. English alphabet has 26 characters and the 26th prime is 101.

Output:

As we can see from the output, the words that have the same key are the anagrams.

In the following Chapters, we'll look at iterators, and algorithms in detail.

Last updated

Was this helpful?