Ways to Overload Default Order in C++’s STL

Summary

In this post, I will introduce some methods to overload the default order in C++’s STL. Please refer to my other post if you are not familiar with Ordered Containers in C++. This post is a helpful reference when solving coding challenges.

Conclusion

You are giving a sequence of pairs, {{5, "five"}, {1, "one"}, {4, "four"}, {3, "three"}, {2, "two"}, {7, "seven"}, {6, "six"} };.
Sort them by the integers in decreasing order. Expected order is {{7,"seven"} {6,"six"} {5,"five"} {4,"four"} {3,"three"} {2,"two"} {1,"one"}}

Function Pointers

C++ has function pointers which you can feed into ordered containers’ template. It is very similar to lambda functions.

bool comp (int a, int b) {
    return a > b;
}
void one() {
    map<int, std::string, decltype(comp)> int2Str(comp);
}
void another() {
    bool(*fn_pt)(int, int) = comp; // fn_pt now is a function pointer with type bool(*)(int, int)
    map<int, std::string, bool(*)(int, int)> int2Str(fn_pt);
}

Lambda Functions

Use lambda functions when you want to do customized sorting or define a global ordered container. For example,

auto comp = [](int i, int j){return i > j;};
map<int, std::string, decltype(comp)> int2Str(comp);

Functors

A functor is pretty much just a class which defines the operator(). That lets you create instances which "look like" a function:

class Compare {
public:
    bool operator() (int const & a, int const &b) const {
        return a.key > b.key;
    }
};
map<int, std::string, Compare> int2Str;
// your Compare will be called like  
Compare comp; // create an instance
comp(a, b)

Customized Class

You can directly define a class and overloads its comparison function.

struct KyeValuePair
{
    int key;
    string val;

    Player(int key_, string val_) :
            key(key_), val(val_)
    {
    }
    bool operator <(const KyeValuePair & anotherInstance) const
    {
        return key > anotherInstance.val;
    }
};

Reference

This blog

Leave a Reply

Your email address will not be published. Required fields are marked *