joachim joachim - 6 months ago 33
C++ Question

Data Structure subject to Comparator

I have defined class that maintains a sorted map of doubles maps that to other data structures. Depending on the use case I want that other to be in ascending or descending order.

struct Book {
std::map<double, Level> levels;

// More complexity ...

void process(Tick &t);

const unsigned amount;

// More stuf ...

Book(const unsigned amount) : levels(), id_price() {}


Ideally, this should be specified in the constructor for Book. I could for example pass
but that won't work because I can't use variables to declare the map
, right? Would it work with templates? I don't want to make it type generic. It should be doubles to not add unnecessary complexity. Ideas?


You can define a custom comparator along these lines:

class comparator {


      bool descending;

      comparator(bool descending) : descending(descending) {}

      bool operator()(double a, double b) const
            return descending ? b < a:a < b;

Then, in your class, define your map specifying this comparator class:

std::map<double, Level, comparator> levels;

Your constructor then needs to explicitly initialize this comparator, and use it to initialize your class's map. std::map's constructor takes an optional parameter, that passes an instance of the comparator class the map will use. Then, for each instance of your Book, its constructor can specify which way its levels will be sorted.

P.S. A double is a poor choice for a map key, but that would be a different question.