1

(Weird this question cannot be asked, because it looks like homework? )

The question is how to define the reset() function in a map with user-defined parameterized comparison struct, which may change the comparison struct for the map. Is it possible at all to define it inside? Should I define copy constructor and other stuff?

I guess indirectly, I could use a pointer outside: every time I need to reset, I just delete the old object and define a new one. But this is ugly. I am wondering whether there are more direct methods.

The following question std::map change key_comp after initialization might be related, but not the same.

I have the following code:

     struct MapStruct {
         struct My_CMP  {
             char _dirc;
             bool operator() (int a, int b) {
                 return _dirc == 'X' ? a < b : a > b;
             }
         };

         char _dirc; 
         map<int, int, My_CMP> _mapStruct;
         MapStruct(char dirc): _dric(dirc), _mapStruct(My_CMP(_dirc)) {}
         void reset(char dirc) {???}             
     };
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
S. Y
  • 173
  • 1
  • 1
  • 7

1 Answers1

1

There's no simple or straightforward way to "reset" the map. You need to create a new map with the new comparator, and then copy all elements from the old map to the new. Then you need to copy the new map to the old map.

Fortunately it's all pretty straightforward when it comes to code, and can be done with a single line:

// Create new map, elements copied from the old,
// with new comparator, and copy over to old map
_mapStruct = map<int, int, My_CMP>(_mapStruct.begin(), _mapStruct.end(), My_CMP(dirc));

This works because the comparison type is the same (My_CMP) for both maps.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks a lot. This works. Why the following does not work (if I don't care the contents)? map newMap(My_CMP(dirc)); _mapStruct = newMap; – S. Y Feb 16 '18 at 04:12
  • 1
    @S.Y Due to [the most vexing parse](https://en.wikipedia.org/wiki/Most_vexing_parse), that declares `newMap` as a function (that takes a `My_CMP` object as arguments, and returns a `map`). – Some programmer dude Feb 16 '18 at 04:40