问题
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-iteratorit1
and an i2-iteratorit2
are equivalent if:
it1==i1.end()
ANDit2==i2.end()
OR
it1
andit2
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