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

淺唱寂寞╮ 提交于 2019-12-11 11:16:13

问题


I have a multi_index_container indexed by 2 indexes. I'm able to find the value by one of them, but is it possible to find the iterator from the other corresponding index?

Example:

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);

The question is, is there an easy way to find the corresponding:

MyStructsContainerByName::iterator itBySalary

which points to the exact same value ( *itById) ?

Thanks, Kalin


回答1:


You're looking for 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.

In your sample

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

you could use

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

or indeed:

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

with exactly the same effect



来源:https://stackoverflow.com/questions/28309136/boostmulti-index-container-find-index-iterator-from-other-index-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!