In C++, you can use a `std::multimap` to store key-value pairs where multiple values can be associated with the same key. However, `std::multimap` automatically keeps its elements sorted based on the keys, and there is no direct method for stable sorting as you would find in vectors or lists. Instead, you can achieve stable sorting by copying the elements into a vector, sorting that vector, and then inserting the sorted elements back into the multimap if needed.
#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
int main() {
// Create a multimap
std::multimap mmap;
mmap.insert({1, "apple"});
mmap.insert({2, "banana"});
mmap.insert({1, "avocado"});
mmap.insert({3, "cherry"});
mmap.insert({2, "blueberry"});
// Copy to a vector to perform stable sort
std::vector<:pair std::string>> vec(mmap.begin(), mmap.end());
std::stable_sort(vec.begin(), vec.end(), [](const auto &a, const auto &b) {
return a.second < b.second; // Sort by value
});
// Clear multimap and insert sorted elements
mmap.clear();
for (const auto &pair : vec) {
mmap.insert(pair);
}
// Output sorted multimap
for (const auto &pair : mmap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?