CodexBloom - Programming Q&A Platform

advanced patterns with std::map and custom comparator leading to duplicate keys in C++14

👀 Views: 444 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
c++ std-map custom-comparator C++

I'm working with a perplexing scenario with `std::map` in C++14 where it seems to allow the insertion of duplicate keys, despite using a custom comparator that should prevent this... Here's a simplified version of my code: ```cpp #include <iostream> #include <map> #include <string> struct CustomComparator { bool operator()(const std::string& lhs, const std::string& rhs) const { return lhs < rhs; } }; int main() { std::map<std::string, int, CustomComparator> myMap; myMap.insert({"key1", 10}); myMap.insert({"key1", 20}); // Shouldn't this unexpected result? for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; } ``` I expected the second insertion (`myMap.insert({"key1", 20});`) to unexpected result or overwrite the existing value based on the comparator, but it actually overwrites the value without any errors, and the output shows `key1: 20` instead of an behavior or retaining the first value. I've verified that my comparator is indeed simple and works correctly for other keys, so I'm baffled as to why it seems to allow duplicates for this specific case. I also tried using `myMap.emplace("key1", 30);` and encountered the same behavior. I've checked the C++ standard and it states that `std::map` should not allow duplicates, so I'm wondering if there's something I'm overlooking in how `std::map` interacts with my custom comparator. Is there a nuance in how comparator functions work that I'm missing, or could this be an scenario with the way I'm inserting the elements? Any insights would be greatly appreciated! I'm working with C++ in a Docker container on Windows 11.