boost::multi_index_container: 从其他索引迭代器中查找索引迭代器

boost::multi_index_container: Find index iterator from other index iterator

我有一个由 2 个索引索引的 multi_index_container。我可以通过其中一个找到值,但是是否可以从另一个对应的索引中找到迭代器?

示例:

struct ById{};
struct ByName{};

typedef multi_index_container<
MyStruct,
indexed_by<
    ordered_unique<tag<ById>, member< MyStruct, int, &MyStruct::id> >,
    ordered_non_unique<tag<BySalary>, member< MyStruct, int, &MyStruct::salary> >
>
> MyStructsContainer;

typedef MyStructsContainer::index<ById>::type MyStructsContainerById;
typedef MyStructsContainer::index<BySalary>::type MyStructsContainerBySalary;

.....

MyStructsContainerById& byId = myStructsContainer.get<ById>();
MyStructsContainerById::iterator itById = byId.find(3);

问题是,有没有简单的方法可以找到对应的:

MyStructsContainerByName::iterator itBySalary

哪个指向完全相同的值 ( *itById) ?

谢谢, 卡林

您正在寻找 boost::multi_index::project

http://www.boost.org/doc/libs/1_36_0/libs/multi_index/doc/reference/multi_index_container.html#projection

Given a multi_index_container with indices i1 and i2, we say than an i1-iterator it1 and an i2-iterator it2 are equivalent if:

  • it1==i1.end() AND it2==i2.end()

OR

  • it1 and it2 point to the same element.

在你的样本中

auto& byId = myStructsContainer.get<ById>();
auto itById = byId.find(3);

你可以使用

MyStructsContainerByName::iterator itBySalary = project<1>(
      myStructsContainer, itById);

或者确实:

auto itBySalary = project<BySalary>(myStructsContainer, itById);

完全一样的效果