我有一个对象:
class Object {
public:
boost::shared_ptr<QString> const& name() const {reutrn _name;}
private:
boost::shared_ptr<QString> _name;
};
还有一个多索引集
typedef
boost::multi_index_container<
Object,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
boost::multi_index::const_mem_fun<
Object,
boost::shared_ptr<QString> const&,
& Object::name>,
StringPointerLess> > >
ObjectSet;
现在如果我想在集合中找到一些东西并且我有QString
我需要复制它以在堆中分配并创建 shared_ptr
。
是否可以避免这种不必要的复制操作,让集合保持原样?
最佳答案
更简单的方法:将以下成员函数添加到您的StringPointerLess
比较谓词:
struct StringPointerLess{
...
bool operator()(boost::shared_ptr<QString> const& x,const QString& y)const{
return *x<y;
}
bool operator()(const QString& x,boost::shared_ptr<QString> const& y)const{
return x<*y;
}
...
};
现在您只需提供所需的 QString
即可进行查找:
IteratorType find( MyContainerType const& container, QString const& key )
{
return container.find( key );
}
这背后的魔法在 special lookup operations section 中有解释。在 Boost.MultiIndex 文档中。
关于c++ - 在一组 shared_ptr<QString> 中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15228895/