notes/CS notes/pages/cpp_std_unordered_map.md
2022-06-14 23:34:11 +08:00

3.2 KiB

Unordered Map

2022-06-10


Data structures:

#DS #unordered_map #hash_table

Difficulty:

#CS_analysis #difficulty-easy

tag:#coding_problem tag:#unordered_map -tag:#template_remove_me 

What is Unordered Map?

I see unordered map as a convenient O(1) hash map:

unordered_map is an associated container that stores elements formed by the combination of key-value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-defined.

Internally unordered_map is implemented using Hash Table, the key provided to map are hashed into indices of a hash table that is why the performance of data structure depends on hash function a lot but on an average, the cost of search, insert and delete from the hash table is O(1).

[!note]- When to use map instead of unordered map In the worst case, its time complexity can go from O(1) to O(n2), especially for big prime numbers. You can read more about this on how-to-use-unordered_map-efficiently-in-c. In this situation, it is highly advisable to use a map instead to avoid getting a TLE error.

How to use

Example taken from g4g

// C++ program to demonstrate functionality of unordered_map
#include <iostream>
#include <unordered_map>
using namespace std;
  
int main()
{
    // Declaring umap to be of <string, double> type
    // key will be of string type and mapped value will
    // be of double type
    unordered_map<string, double> umap;
  
    // inserting values by using [] operator
    umap["PI"] = 3.14;
    umap["root2"] = 1.414;
    umap["root3"] = 1.732;
    umap["log10"] = 2.302;
    umap["loge"] = 1.0;
  
    // inserting value by insert function
    umap.insert(make_pair("e", 2.718));
  
    string key = "PI";
  
    // If key not found in map iterator to end is returned
    if (umap.find(key) == umap.end())
        cout << key << " not found\n\n";
  
    // If key found then iterator to that key is returned
    else
        cout << "Found " << key << "\n\n";
  
    key = "lambda";
    if (umap.find(key) == umap.end())
        cout << key << " not found\n";
    else
        cout << "Found " << key << endl;
  
    //    iterating over all value of umap
    unordered_map<string, double>:: iterator itr;
    cout << "\nAll Elements : \n";
    for (itr = umap.begin(); itr != umap.end(); itr++)
    {
        // itr works as a pointer to pair<string, double>
        // type itr->first stores the key part  and
        // itr->second stores the value part
        cout << itr->first << "  " << itr->second << endl;
     }
}