
Ordered Map C++
The C++ std::map
container from the Standard Template Library (STL) is used to implement an ordered associative container. It stores key-value pairs, where the keys are sorted in a specific order, typically in ascending order by default. The std::map
is implemented as a balanced binary search tree, which ensures efficient insertion, deletion, and retrieval of elements while maintaining the order.
Starting from C++11, the std::map
has been complemented by the std::unordered_map
container, which is implemented as a hash table and provides faster access times for many operations but doesn’t guarantee the same ordering.
Here’s how you can use std::map
in C++:
#include <iostream>
#include <map>
int main() {
// Define a map with int keys and string values
std::map<int, std::string> orderedMap;
// Insert elements
orderedMap[3] = "Three";
orderedMap[1] = "One";
orderedMap[4] = "Four";
orderedMap[2] = "Two";
// Iterate through the map (elements will be ordered by keys)
for (const auto& pair : orderedMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// Find and print an element by key
auto it = orderedMap.find(2);
if (it != orderedMap.end()) {
std::cout << "Element with key 2 found: " << it->second << std::endl;
}
return 0;
}
In this example, the keys in the std::map
will be sorted automatically as you insert elements. The output will show the elements in ascending order of keys.
Keep in mind the following points when using std::map
:
- Elements are stored in a balanced binary search tree, which ensures efficient insertion, deletion, and search operations with a logarithmic time complexity.
- If you need to maintain insertion order, you can consider using
std::unordered_map
from C++11 onwards orstd::map
with a custom comparator in earlier C++ versions. - You can provide a custom comparator function to change the sorting order or to sort based on custom criteria.
- Be aware that maintaining order can come with a performance cost compared to unordered containers like
std::unordered_map
.
Remember to include the <map>
header to use the std::map
container and related functionalities.