Tutorial :comparison function of an associate container data member in class



Question:

I have a class like this:

class MyClass{  public:      MyClass(int Mode);  private:      std::map < int, std::string, CompFunc > data;  };  

The data member must use different comparison function according to Mode argument.

if Mode == 1, then use CompFunc1.  if Mode == 2, then use CompFunc2.  etc.  

but the CompFunc template argument is fixed there, how could I make it dynamically?

thanks.


Solution:1

struct Cmp  {      explicit Cmp(int mode) : mode_(mode) {}        bool operator()(int lhs, int rhs) const      {          switch (mode_)          {              case 1: return CompFunc1(lhs, rhs); break;              case 2: return CompFunc2(lhs, rhs); break;              // etc.          }      }    private:      int mode_;  };    class MyClass  {  public:      explicit MyClass(int Mode) : cmp(mode), data(cmp) {}  private:      Cmp cmp;      std::map<int, std::string, Cmp> data;  };  


Solution:2

You can use the same compare predicate, as for map.

class MyClass  {      CompFunc cmp;      map<int, std::string, CompFunc> data;  public:      MyClass(int Mode) : cmp( get_cmpfunc(Mode) ), data(cmp) {...}      bool operator == (...)      {          cmp(...);      }  };  


Solution:3

Write a wrapper class/function that conforms to the right interface but dispatches to the correct function depending on the mode (or other variables).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »