SimplifyC++ Article
comprehensive guide on using STL map and unordered_map in modern C++, along with a comparison to JavaScript Map
Concise guide on using STL map and unordered_map in modern C++, along with a comparison to JavaScript Map:
STL map
Ordered associative container: Elements are stored in a sorted order based on their keys.
Implementation: Typically uses a red-black tree.
Key operations:
insert: Inserts a new key-value pair.find: Searches for an element with a given key.erase: Removes an element with a given key.count: Checks if a key exists.begin,end: Iterators to access the first and last elements.
Example:
int main() { std::map<std::string, int> myMap;
// Insert elements myMap["apple"] = 10; myMap["banana"] = 20; myMap["orange"] = 30;
// Find an element std::map<std::string, int>::iterator it = myMap.find("banana"); if (it != myMap.end()) { std::cout << it->first << ": " << it->second << std::endl; }
// Erase an element myMap.erase("apple");
// Iterate over elements for (auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; }
return 0;}STL unordered_map
Unordered associative container: Elements are stored in a hash table.
Key operations: Similar to
map, but without the sorted order guarantee.Performance: Generally faster than
mapfor large datasets, especially when frequent lookups are needed.
Example:
int main() { std::unordered_map<std::string, int> myMap;
// Insert elements myMap["apple"] = 10; myMap["banana"] = 20; myMap["orange"] = 30;
// Find an element std::unordered_map<std::string, int>::iterator it = myMap.find("banana"); if (it != myMap.end()) { std::cout << it->first << ": " << it->second << std::endl; }
// Erase an element myMap.erase("apple");
// Iterate over elements (order is not guaranteed) for (auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; }
return 0;}Differences from JavaScript Map
Key types: C++
mapandunordered_mapcan use any type as a key, while JavaScriptMaponly supports primitive types and objects.Value types: C++ can store any type as a value, while JavaScript
Mapstores only objects.Performance: C++
mapandunordered_mapare generally faster for large datasets due to their efficient implementations.Syntax: The syntax for accessing elements and iterating over key-value pairs is slightly different in C++ compared to JavaScript.
both STL map and unordered_map provide efficient ways to store and retrieve key-value pairs in C++. The choice between the two depends on whether you need sorted order or faster lookups. Understanding their differences from JavaScript Map will help you use them effectively in your C++ projects.