Standard Template Library STL
Published by
sanya sanya
In C++, the Standard Template Library (STL) provides the ‘unordered_map’ container, which implements a hash table-based associative array. It allows efficient key-value lookup and provides several member functions for manipulating and accessing elements.
Creating an ‘unordered_map’:
Code:
#include
#include <unordered_map>
using namespace std;
int main() {
unordered_map<string, int> myMap; // Create an empty unordered_map
return 0;
}
1. Inserting elements: Using insert function or [] operator
- The ‘insert()’ function takes a pair of the key and value.
- The ‘[]’ operator can be used to access or insert elements. If the key doesn't exist, a new element is inserted.
Code:
unordered_map<string, int> myMap;
myMap.insert(make_pair("apple", 10));
myMap["banana"] = 20;
2. Accessing and modifying elements:
Code:
unordered_map<string, int> myMap = {{"apple", 10}, {"banana", 20}};
int count = myMap["apple"]; // Access the value associated with the key "apple"
myMap["banana"] = 30; // Modify the value associated with the key "banana"
3. Checking existence and retrieving size:
-Count() function to check if a key exists in the ‘unordered_map’. It returns 1 if the key exists, 0 otherwise.
- The size() function returns the number of elements in the ‘unordered_map’.
Code:
unordered_map< string, int> myMap = {{"apple", 10}, {"banana", 20}};
bool exists = myMap.count("apple"); // Check if the key "apple" exists
size_t numElements = myMap.size(); // Get the number of elements in the unordered_map
4. Iterating over elements:
- You can iterate over the ‘unordered_map’ using iterators.
- Each element in the ‘unordered_map’ is represented as a ‘pair’ containing the key-value pair.
Code:
unordered_map<string, int> myMap = {{"apple", 10}, {"banana", 20}};
for (const auto& pair : myMap) {
cout << pair.first << ": " << pair.second << endl;
}
5. Erasing elements:
- The ‘erase()’ function removes the element associated with the given key.
Code:
unordered_map<string, int> myMap = {{"apple", 10}, {"banana", 20}};
myMap.erase("apple"); // Remove the element with the key "apple"
Library
WEB DEVELOPMENT
FAANG QUESTIONS