Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map change key_comp after initialization

Tags:

c++

stl

stdmap

It is possible to change the comparison method of a std::map after it has been created and initialized? Or maybe only after it has been created??

I want to alter somehow the behavior of a class that contains a map that I cannot change the definition. I want to change it's comparison behavior maybe by passing another map.

like image 434
djWann Avatar asked Dec 18 '12 14:12

djWann


People also ask

Can I change value in map C++?

To update an existing value in the map, first we will find the value with the given key using map::find() function. If the key exists, then will update it with new value.

Does insert overwrite map C++?

insert() doesn't overwrite.

Does map sort automatically C++?

By default, a Map in C++ is sorted in increasing order based on its key.

Does map maintain insertion order C++?

C++ hash map and hash set which preserves the order of insertion. The ordered-map library provides a hash map and a hash set which preserve the order of insertion in a way similar to Python's OrderedDict. When iterating over the map, the values will be returned in the same order as they were inserted.


1 Answers

Maybe it is possible, this is untested:

  1. Define your own custom comparator, which internally has a pointer to the real implementation of the comparison function
  2. Pass an instance of this to the constructor of the map (you have to type the map using this comparator too.)
  3. Set the real implementation later (before using the map), if you set it after, you don't know the impact on the internals...

Have tested, and it is possible to do the above, however changing the comparison function if there are items in the tree can be disastrous...

Anyway - it all sounds too fishy....

like image 142
Nim Avatar answered Nov 07 '22 10:11

Nim