简体   繁体   English

如何从multi_index_container获取倒数第二个元素

[英]How to get the second to last element from a multi_index_container

I have a boost::multi_index_container indexed by hashed_unique and sequenced . 我有一个boost::multi_index_containerhashed_unique索引并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? 我可以使用此myIter获取上一个元素的迭代器吗?

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?
}

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. 请注意,对于倒数第二个位置,可以使用相同的技术,这可能使您无需保留hashOfLast变量。

Can I use this myIter to get an iterator to the previous element? 我可以使用此myIter获取上一个元素的迭代器吗?

No (unless you resort to iterator projection as shown above), because of two reasons: 否(除非您如上所述使用迭代器投影),原因有两个:

  • Hashed index iterators (unlike those of sequenced indices) are not bidirectional (incrementable and decrementable), just forward (incrementable). 哈希索引迭代器(与顺序索引的迭代器不同)不是双向的(可递增和可递减),而是向前的(可递增的)。
  • Even if 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. 即使myIter递减,也不会指向顺序索引中倒数第二个元素:两个索引中的遍历顺序是完全不相关的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM