c++ - 在一组 shared_ptr 中找到一个值

标签 c++ set c++14 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_ptrint 进行比较的附加逻辑:

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

关于c++ - 在一组 shared_ptr 中找到一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32610446/

相关文章:

c++ - 在C++14模式下用clang for libstdc++编译regex程序报错

linux - 在 linux Bash 中设置

c++ - 我可以知道为什么这段代码没有给出任何输出吗?

c++ - 集合和字典( map )的一个类

c++ - 如何验证 C++ 编译器是否将函数扩展为内联?

c++ - 统一初始化中的广义 lambda 捕获无法编译

c++ - 如何将一个类的部分公共(public)接口(interface)限制为只有一个类?

c++ - 关于 View 矩阵和视锥剔除

java - Android App中的C/C++代码是如何执行的?

python - 在 Mysql 或 Python 中良好的实现,可以增加有限的值集