Search code examples
c++setc++14shared-ptr

Find a value in a set of shared_ptr


I have a set of shared_ptr and would like to find a value in it:

typedef std::shared_ptr<int> IntPtr;

struct Compare {
  bool operator() (const IntPtr& a, const IntPtr& b) {
    return *a < *b;
  }
};
std::set<IntPtr, Compare> s;

auto x = std::make_shared<int>(3);
s.insert(x);

bool found = s.find(std::make_shared<int>(3)) != s.end();

It's working, but not efficient - it need to new a temp pointer every time when trying to find a value.

Is there any other way for it?

Looks like Searching in a set of shared_ptr<QString> has some ideas that might help?


Solution

  • (In C++14) Make your comparator a transparent one and define additional logic for comparing stored shared_ptrs with ints:

    struct Compare 
    {
        using is_transparent = void;
        //    ~~~~~~~~~~~~~^
    
        bool operator() (const IntPtr& a, const IntPtr& b) const
        {
            return *a < *b;
        }
    
        bool operator() (const IntPtr& a, int b) const
        {
            return *a < b;
        }
    
        bool operator() (int a, const IntPtr& b) const
        {
            return a < *b;
        }
    };
    

    DEMO