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?
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.
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.
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.
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.
(In C++14) Make your comparator a transparent one and define additional logic for comparing stored shared_ptr
s with int
s:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With