Initializing multiset with custom comparison function in C++

前端 未结 4 1307
独厮守ぢ
独厮守ぢ 2021-02-04 14:50

Consider following comparison function:

bool compare(std::shared_ptr &lhs, std::shared_ptr &rhs){
   return lhs->val         


        
4条回答
  •  臣服心动
    2021-02-04 15:04

    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 &lhs, 
                        std::shared_ptr &rhs) const {
            return lhs->value < rhs->value;
        }
    };
    
    std::multiset, compare> myset;
    

提交回复
热议问题