std::map with custom comparator not preserving order of elements when using insert_or_assign in C++17
I'm deploying to production and I'm converting an old project and I'm experiencing an issue with `std::map` in C++17 where I'm using a custom comparator but the order of the elements doesn't seem to be preserved after using `insert_or_assign`. I have a custom struct as the key which contains two integers, and the comparator compares these integers based on certain conditions. After inserting several elements, I noticed that when I call `insert_or_assign`, the order of the elements seems to change unexpectedly. Hereβs a simplified version of my code: ```cpp #include <iostream> #include <map> struct Key { int x; int y; bool operator<(const Key& other) const { return (x < other.x) || (x == other.x && y < other.y); } }; int main() { std::map<Key, std::string> myMap; myMap.insert_or_assign({2, 3}, "First"); myMap.insert_or_assign({1, 5}, "Second"); myMap.insert_or_assign({2, 1}, "Third"); for (const auto& pair : myMap) { std::cout << "Key: (" << pair.first.x << ", " << pair.first.y << ") - Value: " << pair.second << '\n'; } return 0; } ``` When I run this code, I expect the output to be in the order of the keys based on their `x` and `y` values. However, I see: ``` Key: (1, 5) - Value: Second Key: (2, 3) - Value: First Key: (2, 1) - Value: Third ``` Which is not what I intended given the comparator logic. Iβve confirmed that the comparator is defined correctly, and I also checked that `std::map` maintains a sorted order based on the keys. Is there an issue with how I'm using `insert_or_assign`, or could it be related to how the comparator is defined? Any guidance on how to ensure that the elements are stored in the intended order would be greatly appreciated. The project is a web app built with Cpp. What am I doing wrong? Thanks, I really appreciate it!