在一组shared_ptr中查找值

时间:2015-09-16 13:46:01

标签: 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();

它正在工作,但效率不高 - 每次尝试查找值时都需要新建一个临时指针。

还有其他办法吗?

看起来Searching in a set of shared_ptr<QString>有一些可能有用的想法吗?

2 个答案:

答案 0 :(得分:15)

(在C ++ 14中)制作比较器a transparent one并定义用于将存储的shared_ptrint 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

答案 1 :(得分:0)

使用单线程程序,您可以减少单个全局分配的开销:

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,然后创建该类的线程局部静态。