Reputation: 1779
I have a boost::multi_index_container
indexed by hashed_unique
and sequenced
. How can I get the second from the last element from this container?
struct MyContainer : public mi::multi_index_container<
MyStruct,
mi::indexed_by<
mi::hashed_unique<
mi::tag<hashed>,
%some stuff%,
%some stuff%,
%some stuff%>
>,
mi::sequenced<mi::tag<sequenced> >
>
>
{ };
As the container is hashed, I can find any element by its hash. But in my case, I do not know the hash of the second-to-last element. However, I know the hash of the last element and hence can get the last element.
MyContainer::iterator myIter = m_table.find(hashOfLast);
Can I use this myIter
to get an iterator to the previous element?
Edit:
Can I do something like this?
MyContainer::nth_index<1>::type& seqIdx = m_table.get<1>();
auto current = seqIdx.rbegin();
auto last = seqIdx.rend();
if(current != last){
current++;
//How to get the hash of this element now?
}
Upvotes: 1
Views: 770
Reputation: 5658
You can use iterator projection as follows:
MyContainer::index<sequenced>::type::iterator it=
m_table.get<sequenced>().end(); // iterator to end of sequenced index
--it;--it; // two steps back
MyContainer::iterator myIter=m_table.project<hashed>(it); // project into the hashed index
Note that the same technique can be used for the one-to-last position, which might dispense you with the need to keep your hashOfLast
variable.
Can I use this
myIter
to get an iterator to the previous element?
No (unless you resort to iterator projection as shown above), because of two reasons:
myIter
coud be decremented, it wouldn't point to the element at the second-to-last position in the sequenced index: traversal orders in both indices are completely unrelated.Upvotes: 3