c++ - 在一组 shared_ptr<QString> 中搜索

标签 c++ boost shared-ptr boost-multi-index multi-index

我有一个对象:

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/

相关文章:

C++ 创建解析器

c++ - 什么类型的转换从 parent 到 child ?

c++ - 使用 shared_ptr 将 base 抽象为 boost.python 的持有者

android - 构建android项目产生make error 2

c++ - 在 C++ 中,哪个是最昂贵的,删除最后一个元素或调整 vector 的大小?

c++ - 编写一个使多个容器看起来像一个的迭代器

c++ - boost::ptr_container 和 std::vector<shared_ptr>

c++ - boost::hash_combine 在 Release模式下失败

c++ - 替换 shared_ptr<T> 中对对象的所有引用

c++ - 在 tr1::shared_ptr 的 vector 中查找元素