我有一组 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_ptr
与 int
进行比较的附加逻辑:
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;
}
};
关于c++ - 在一组 shared_ptr 中找到一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32610446/