Deq*_*ing 8 c++ set shared-ptr
我有一套,shared_ptr并希望在其中找到一个值:
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();
Run Code Online (Sandbox Code Playgroud)
它工作,但效率不高 - 每次尝试查找值时都需要新建一个临时指针.
还有其他办法吗?
看起来像在一组shared_ptr <QString>中搜索有一些可能有帮助的想法?
Pio*_*cki 15
(在C++ 14)让您的比较器一个透明一个并定义附加的逻辑用于比较存储shared_ptrs的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;
}
};
Run Code Online (Sandbox Code Playgroud)