Search code examples
c++boostshared-ptrboost-multi-indexmulti-index

Searching in a set of shared_ptr<QString>


I have an object:

class Object {
public:
  boost::shared_ptr<QString> const& name() const {reutrn _name;}
private:
  boost::shared_ptr<QString> _name;
};

And a multi_index set

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;

Now If I want to find something in the set and I have QString I need to make a copy of it to allocate in heap and create shared_ptr.

Is it possible to avoid this unnecessary copy operation, leaving the set as it is?


Solution

  • A simpler way: add the following member functions to your StringPointerLesscomparison predicate:

    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;
      }
      ...
    };
    

    and now you can lookup by simply providing the desired QString:

    IteratorType find( MyContainerType const& container, QString const& key )
    {
       return container.find( key );
    }
    

    The magic behind this is explained at the special lookup operations section in Boost.MultiIndex documentation.