Search code examples
c++setshared-ptr

c++ set and shared_ptr


I have class X like:

class X {
    public:
        bool operator<(const SCN& other) const;
};

Then I have the following code:

std::multiset<std::shared_ptr<X>> m;

My questions are:

  1. how the data in m is ordered? the address of X(shared_ptr) or the X.operator<? If it is ordered by address of X, how can I make it order by X.operator<?

  2. for this m, if I want to access its elements from smallest to biggest, can the following code guarantee that? If not, How?

    for (auto& i : m) {
        f(i);
    }
    

Solution

  • Your set is ordered based on your key_type which is std::shared_ptr<X>. As your std::shared_ptr<X> is comparable, the ordering of the std::shared_ptr prevails.

    For the sake of reference, multiset is defined as

    template<
        class Key,
        class Compare = std::less<Key>,
        class Allocator = std::allocator<Key>
    > class multiset;
    

    As can be seen, typename Compare is std::less<Key> and std::less should overload the function overload which would possibly be implemented as

    constexpr bool operator()(const T &lhs, const T &rhs) const 
    {
        return lhs < rhs;
    }
    

    both lhs and rhs is of type T which in this case is Key which is the type that we have instantiated multiset with which is std::shared_ptr<X>.