Sort a std::list with myclass::operator<(myclass &other)

后端 未结 5 591
一生所求
一生所求 2021-01-12 04:31

I have a std::list and in my class I have myclass::operator<(myclass &other) defined.

I use the std::list.sort

5条回答
  •  再見小時候
    2021-01-12 05:28

    Several answers propose using a predicate that explicitly takes two pointers; this will work for your current case where you have a container of raw pointers, but it won't work for any other dereferenceable type, like smart pointers or iterators.

    Why not go the more general route and match any type?

    struct indirect_compare
    {
        template 
        bool operator()(const T& lhs, const T& rhs) const 
        {
            return *lhs < *rhs;
        }
    }
    

    While a const reference is unnecessary for a T*, it is necessary for smart pointer types that are relatively expensive to copy (e.g. std::shared_ptr) or impossible to copy (e.g. std::unique_ptr).

    Alternatively, you might consider using something like Boost's indirect_iterator, which moves the indirection into the iterator and can make for much cleaner code.

提交回复
热议问题