gpt4 book ai didi

c++ - 无法理解 multi_index

转载 作者:行者123 更新时间:2023-11-28 08:21:40 25 4
gpt4 key购买 nike

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 实现吗?

最佳答案

在您的例子中,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
}

关于c++ - 无法理解 multi_index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5612944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com