gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:25:11 25 4
gpt4 key购买 nike

我有一组 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com