Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 701
Deqing Avatar asked Sep 16 '15 13:09

Deqing


People also ask

What does shared_ptr get () do?

A shared_ptr may share ownership of an object while storing a pointer to another object. get() returns the stored pointer, not the managed pointer.

How many bytes is a shared_ptr?

In a typical implementation, std::shared_ptr holds only two pointers. So 1000 shared pointers take up 1000 * 2 * sizeof(pointer) bytes of memory. Size of a pointer is 4 bytes on all 32-bit systems that follow ILP32 data model.

Can you return a shared_ptr?

So the best way to return a shared_ptr is to simply return by value: shared_ptr<T> Foo() { return shared_ptr<T>(/* acquire something */); }; This is a dead-obvious RVO opportunity for modern C++ compilers.

What is a shared_ptr in C++?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.


1 Answers

(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

like image 154
Piotr Skotnicki Avatar answered Oct 06 '22 23:10

Piotr Skotnicki