Sort order of std :: map depending on input value

I know that you cannot change the display order of the map after the announcement. Instead, I try to do this in a structure:

struct MyStruct
{
    std::map<int, double>* my_map;

    MyStruct(bool dir)
    {
        if(dir)
        {
            my_map = new std::map<int, double, std::less<int> >;
        }
        else
        {
            my_map = new std::map<int, double, std::greater<int> >;
        }
    }
}

This does not work and complains that I am changing the type in else. Is there any way around this? The only way I can think of is to write my own comparator and create an encapsulating object bool dirthat seems superfluous.

+3
source share
2 answers

std::map transfers the comparison object as a template parameter, so to accomplish what you want, you need a type that you can change at runtime.

    struct MoreOrLess
    {
      bool useLess;
      template <class T, class U>
      bool operator()(const T &t, const U &u) const
      {
        if(useLess) return t < u;
        else return t > u;
      }
    };

    struct MyStruct
    {
        std::map<int, double, MoreOrLess> my_map;

        MyStruct(bool dir) :my_map(MoreOrLess{dir}) {}
    };

, ( std::map) std::less std::greater.

+5

, , , :

struct MyStruct
{
    typedef std::function<bool(int,int)> Predicate;
    std::map<int,double,Predicate> my_map;

    static Predicate predicateFor(bool dir)
    {
        if (dir) return std::less<int>();
        return std::greater<int>();
    }

    MyStruct(bool dir) : my_map(predicateFor(dir)) { }
};
0

All Articles