How do I remove duplicates with std::multimap?

In C++, std::multimap allows for the storage of multiple values under the same key. However, if you want to remove duplicates from a std::multimap, you can do so by using an algorithm to traverse the multimap and erase duplicate entries. Below is an example demonstrating how to remove duplicates from a std::multimap.

#include <iostream> #include <map> #include <set> int main() { // Create a multimap and insert some duplicate entries std::multimap m; m.insert(std::make_pair(1, "apple")); m.insert(std::make_pair(1, "apple")); // duplicate m.insert(std::make_pair(2, "banana")); m.insert(std::make_pair(3, "orange")); m.insert(std::make_pair(3, "orange")); // duplicate // Use a set to track unique entries std::set<:pair std::string>> uniqueEntries; // Traverse the multimap and insert only unique entries into the set for (const auto& entry : m) { uniqueEntries.insert(entry); } // Clear the original multimap m.clear(); // Insert back only the unique entries for (const auto& entry : uniqueEntries) { m.insert(entry); } // Print the multimap after removing duplicates for (const auto& entry : m) { std::cout << entry.first << ": " << entry.second << std::endl; } return 0; }

C++ std::multimap remove duplicates C++ examples