unordered_map is an associated container that stores elements formed by the combination of key-value and a mapped-value. Both key-value and mapped-value can be any type predefined or user-defined.
The key value is used to uniquely identify the element
The mapped value is the content associated with the key
// C++ program to demonstrate functionality of unordered_map #include<iostream> #include<unordered_map> usingnamespace std;
intmain() { // 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;
// 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; } return0; }
A practical problem based on unordered_map – given a string of words, find frequencies of individual words.
1 2 3 4 5 6 7
Input : str = "geeks for geeks geeks quiz practice qa for"; Output : Frequencies of individual words are (practice, 1) (for, 2) (qa, 1) (quiz, 1) (geeks, 3)
// C++ program to find freq of every word using // unordered_map #include<iostream> #include<unordered_map> #include<string> #include<sstream> usingnamespace std;
// Prints frequencies of individual words in str voidprintFrequencies(const string &str) { // declaring map of <string, int> type, each word // is mapped to its frequency unordered_map<string, int> wordFreq;
// breaking input into word using string stream stringstream ss(str); // Used for breaking words string word; // To store individual words while (ss >> word) wordFreq[word]++;
// now iterating over word, freq pair and printing // them in <, > format unordered_map<string, int>:: iterator p; for (p = wordFreq.begin(); p != wordFreq.end(); p++) cout << "(" << p->first << ", " << p->second << ")\n"; }