Kiko
Kiko

Reputation: 359

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

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

Upvotes: 1

Views: 434

Answers (1)

sehe
sehe

Reputation: 393064

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

Upvotes: 1

Related Questions