簡體   English   中英

如何從multi_index_container獲取倒數第二個元素

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

我有一個boost::multi_index_containerhashed_unique索引並sequenced 如何從該容器的最后一個元素中獲取第二個元素?

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> >
    >
>
{ };

由於容器是散列的,因此我可以通過其散列找到任何元素。 但就我而言,我不知道倒數第二個元素的哈希值。 但是,我知道最后一個元素的哈希,因此可以獲取最后一個元素。

MyContainer::iterator myIter = m_table.find(hashOfLast);

我可以使用此myIter獲取上一個元素的迭代器嗎?

編輯:

我可以做這樣的事情嗎?

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

您可以按以下方式使用迭代器投影

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

請注意,對於倒數第二個位置,可以使用相同的技術,這可能使您無需保留hashOfLast變量。

我可以使用此myIter獲取上一個元素的迭代器嗎?

否(除非您如上所述使用迭代器投影),原因有兩個:

  • 哈希索引迭代器(與順序索引的迭代器不同)不是雙向的(可遞增和可遞減),而是向前的(可遞增的)。
  • 即使myIter遞減,也不會指向順序索引中倒數第二個元素:兩個索引中的遍歷順序是完全不相關的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM