在一组 shared_ptr 中查找一个值

Find a value in a set of 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> 有一些可能有用的想法?

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

DEMO

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

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();
}

免责声明:代码未经编译器处理。

对于线程,您可以考虑将上面的方法设为 class 的方法,将 p 作为成员,然后将 class 设为线程局部静态。