Initializing multiset with custom comparison function in C++

Jason picture Jason · Sep 10, 2013 · Viewed 8.2k times · Source

Consider following comparison function:

bool compare(std::shared_ptr<myObject> &lhs, std::shared_ptr<myObject> &rhs){
   return lhs->value < rhs->value;
}

Now idea is to initialize a multiset of type std::shared_ptr<myObject> which orders elements with above function. So from book i read it should be done like this:

std::multiset<std::shared_ptr<myObject>, decltype(compare)*> myset{compare};

QUESTION:

My question is, in the declaration i understad a function pointer is passed to refer to compare function, but why are we initiazling the set wtih {compare}?? what is its importance and why is it necessary to do so like this??

Answer

Mike Seymour picture Mike Seymour · Sep 10, 2013

Because the set needs a comparison functor to work with. If you don't specify one, it will make a default-constructed one. In this case, since you're using a function-pointer type, the default-constructed one will be a null pointer, which can't be called; so instead, you have to provide the correct function pointer at run time.

A better approach might be to use a function class type (a.k.a. functor type); then the function call can be resolved at compile time, and a default-constructed object will do the right thing:

struct compare {
    bool operator()(std::shared_ptr<myObject> &lhs, 
                    std::shared_ptr<myObject> &rhs) const {
        return lhs->value < rhs->value;
    }
};

std::multiset<std::shared_ptr<myObject>, compare> myset;