std::unordered_map

suggest change

Using std::unordered map

Introduction

std::unordered_map is an associative container that stores unique keys and a mapped value for each key. Keys and values may use built-in or user-defined types, provided that the key type supports equality comparison and hashing.

Remarks

Elements are organized into buckets according to their hash values rather than kept in sorted order. Lookup, insertion, and removal take constant time on average, but can take linear time in the worst case. Unlike std::map, an unordered_map does not provide sorted iteration. The [] operator inserts a value-initialized mapped value when the key is absent; use find, contains (C++20), or at when insertion is not intended.

Declaration and usage

This example maps strings to integers:

unordered_map<string, int> first; //declaration of the map 
first["One"] = 1; // [] operator used to insert the value 
first["Two"] = 2;
first["Three"] = 3;
first["Four"] = 4;
first["Five"] = 5;

pair <string,int> bar = make_pair("Nine", 9); //make a pair of same type
first.insert(bar); //can also use insert to feed the values

Some basic methods

unordered_map<data_type, data_type> variable_name; //declaration

variable_name[key_value] = mapped_value; //inserting values

variable_name.find(key_value); // iterator to the element, or end() if the key is absent

variable_name.begin(); // iterator to one element; the order is not sorted

variable_name.end(); // iterator to the last + 1 element

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents