无法理解multi_index

时间:2011-04-10 15:58:15

标签: c++ boost boost-multi-index

class ObjectStorage
{
    private:
        std::string objName;
        int zIndex;

        // Reference for the Object interface
        boost::shared_ptr<Object> mCppObject;

        // Reference for the Python interface
        boost::python::object mPythonObject;

    public:
        ObjectStorage(const std::string &name, int zIndex_, boost::shared_ptr<Object> cpp, boost::python::object python)
            : objName(name), zIndex(zIndex_),
              mCppObject(cpp), mPythonObject(python) {}

        std::string getName() const { return objName; };
        int getZIndex() const { return zIndex; }

        boost::shared_ptr<Object> getCppObject() const { return mCppObject; }
        boost::python::object getPythonObject() const { return mPythonObject; }
};

// Tagging for multi_index container
struct tag_zindex {};
struct tag_name {};
struct tag_cpp {};
struct tag_py {};

typedef boost::multi_index_container<ObjectStorage,
            bmi::indexed_by<
                // ZIndex
                bmi::ordered_non_unique<
                    bmi::tag<tag_zindex>,
                    bmi::const_mem_fun<ObjectStorage, int, &ObjectStorage::getZIndex>
                >,

                // Name
                bmi::ordered_unique<
                    bmi::tag<tag_name>,
                    bmi::const_mem_fun<ObjectStorage, std::string, &ObjectStorage::getName>
                >,

                // CPP reference
                bmi::ordered_non_unique<
                    bmi::tag<tag_cpp>,
                    bmi::const_mem_fun<ObjectStorage, boost::shared_ptr<Object>, &ObjectStorage::getCppObject>
                >,

                // Python reference
                bmi::ordered_unique<
                    bmi::tag<tag_py>,
                    bmi::const_mem_fun<ObjectStorage, boost::python::object, &ObjectStorage::getPythonObject>
                >
            >
        > ObjectWrapperSet;

如果multi_index中的第一个索引是正确的:在容器内排序对象引用ZIndex值,我不确定另一个。我需要这样的功能: 按ZIndex排序,但在迭代时返回getCppObject。是否有可能不仅设置排序,而且可以在访问时产生结果?

另外,例如tag_py我希望遍历所有getPythonObject,而不是ObjectStorage。这对multi_index真的有用吗?

1 个答案:

答案 0 :(得分:1)

在您的情况下,multi_index_container包含ObjectStorage个对象的实例。因此,您可以通过它迭代任意顺序并调用ObjectStorage类的任何函数。

例如,使用tag_py标记迭代:

ObjectWrapperSet ow_set;

ObjectWrapperSet::index_const_iterator<tag_py>::type it = ow_set.get<tag_py>().begin();
for ( ; it != ow_set.get<tag_py>().end(); ++it ) {
  const ObjectStorage& os = *it; // note `it` is the iterator for ObjectStorage
  // now you can do
  boost::python::object po = os.getPythonObject();
  // or
  boost::python::object po = it->getPythonObject();
}

使用tag_zindex代码:

ObjectWrapperSet::index_const_iterator<tag_zindex>::type it = ow_set.get<tag_zindex>().begin();
for ( ; it != ow_set.get<tag_zindex>().end(); ++it ) {
  boost::shared_ptr<Object> cpp_obj = it->getCppObject();
  // do something
}