Inserting a user defined key in a C++ map
-
Hi Guys, I have recently came across one scenario where I have to insert a user defined key in a c++ map. that class looks like this class key { int id; string name; }; map is like map I'll overload "operator<" function and will sort out based on "id" which will works fine, but the condition is like, if there are 2 entry with same ID but with a different name, for ex. {"50", Jack} and {"50", John} As both the values have SAME ID and different name, map should make an entry for both. Only in the case of combination of same ID and same name, it shouldn't allow the entry. bool operator<(key& temp) { if(id < temp.id) { return true; } if( id == temp.id) return name < temp.name; } its not working properly, its overriding the last entry if same ID is there. Please help me out
-
Hi Guys, I have recently came across one scenario where I have to insert a user defined key in a c++ map. that class looks like this class key { int id; string name; }; map is like map I'll overload "operator<" function and will sort out based on "id" which will works fine, but the condition is like, if there are 2 entry with same ID but with a different name, for ex. {"50", Jack} and {"50", John} As both the values have SAME ID and different name, map should make an entry for both. Only in the case of combination of same ID and same name, it shouldn't allow the entry. bool operator<(key& temp) { if(id < temp.id) { return true; } if( id == temp.id) return name < temp.name; } its not working properly, its overriding the last entry if same ID is there. Please help me out
Try std::multimap. It does exactly what you want.
Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.