CodexBloom - Programming Q&A Platform

Unexpected behavior with std::map when using custom comparator in C++14

πŸ‘€ Views: 50 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-28
c++ stdmap customcomparator C++

I've encountered a strange issue with This might be a silly question, but I'm relatively new to this, so bear with me. I'm encountering unexpected behavior when using a custom comparator with `std::map` in C++14. I designed a custom comparator to allow storing keys of a custom struct, but when I attempt to insert elements, I notice that certain keys are being treated as equivalent even though they shouldn't be. Here’s a simplified version of my struct and comparator: ```cpp struct MyStruct { int id; std::string name; }; struct MyStructComparator { bool operator()(const MyStruct &a, const MyStruct &b) const { return a.id < b.id; // I want to compare only by 'id' } }; ``` When I declare my `std::map`, I set it up like this: ```cpp std::map<MyStruct, int, MyStructComparator> myMap; ``` However, when I insert elements like this: ```cpp myMap[{1, "Alice"}] = 100; myMap[{1, "Bob"}] = 200; // This key is treated as a duplicate! ``` I expected the second insertion to overwrite the first, but instead, I'm getting an error: `error: duplicate key in map`. I’ve verified that the `id` values are indeed the same but with different names. However, I want to keep both entries since they have different meanings despite having the same `id`. I thought the custom comparator would prevent this confusion, but it seems to only consider `id` for uniqueness. I also tried changing the comparator to include `name` in the comparison: ```cpp bool operator()(const MyStruct &a, const MyStruct &b) const { return std::tie(a.id, a.name) < std::tie(b.id, b.name); } ``` But this approach seems to change the behavior of my map in unexpected ways as it also introduces precedence based on `name`, which isn't what I want. Is there a way to maintain uniqueness based solely on `id` while still allowing different values associated with the same key? What are the best practices here? Any help would be greatly appreciated! This is part of a larger web app I'm building. Thanks in advance! For context: I'm using C++ on Linux. How would you solve this? I'm working in a Windows 10 environment.