我有一套 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();
它能用,但效率不高 -- 它每次都需要新建一个临时指针来寻找一个值。
有其他方法吗?
看起来像 在一组shared_ptr<QString>中搜索。 有一些想法可能会有帮助?
(在C++14中) 让你的比较器 a 透明的 一个 并定义额外的逻辑来比较存储的 shared_ptr
与 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;
}
};
在单线程程序中,你可以将开销减少到一次全局分配。
using Int_ptr_set = std::set<IntPtr, Compare>;
auto find( int const v, Int_ptr_set const& values )
-> bool
{
static IntPtr p = std::make_shared<int>( 0 );
*p = v;
return values.find( p ) != values.end();
}
声明:代码未被编译器的手接触过。
对于线程,你可以考虑把上面的内容做成一个类的方法,用 p
作为成员,然后将该类的线程本地静态化。