I have a set of data which in some occasion I need to sort them in one way and some occasion in another way. For example, suppose the data set is a set of strings,{“abc”, “dfg”,…}. Sometimes I need to sort them in alphabetic order and sometimes by comparing their length.
Initially I used std::set as a container of my data and implemented 2 comparators, hoping that I can change the comparator of the set on the fly, cause the data is huge and it’s not a good idea to copy it from one set to another..I just want to sort it using different comparators from time to time. Is this possible or what’s the right way to do it?
You have to specify the comparator of
std::setat construction time.As a solution, I would maintain two ‘index’ sets instead, each referring to the actual collection. This would yield the greatest flexibility. To keep everything together, I suggest you wrap it up in a single class:
Boost library has such a class: Multiindex.