2013-04-24 145 views
2

我有如下定義:的multi_index_container刪除最後一個元素

typedef boost::multi_index_container< 
    boost::shared_ptr<Temp>, 
    boost::multi_index::indexed_by< 
    boost::multi_index::ordered_non_unique< boost::multi_index::const_mem_fun<Temp, unsigned int, &Temp::getParam> > 
    > 
    > RequestsContainer; 

我需要從該容器中取出(POP)最後一個元素。我怎樣才能做到這一點? reverse_iterator不能與erase()一起使用。

謝謝

回答

2

使用「序列<>」你類似於「的std ::名單」語義索引看到提振codumentationcode example。改變你的「類型定義」到:

typedef boost::multi_index_container< 
    boost::shared_ptr<Temp>, 
    boost::multi_index::indexed_by< 
    boost::multi_index::sequenced<>, 
    boost::multi_index::ordered_non_unique< 
     boost::multi_index::const_mem_fun<Temp, unsigned int, &Temp::getParam> 
    > 
    > 
> RequestsContainer; 

,然後有「的std ::名單」的額外的語義,你會得到一個雙向迭代結束和減少它作爲每this question,這樣的:

RequestsContainer r; 
/* ... fill r ... */ 
assert(!r.empty); 
auto iter = r.end(); // from sequenced<> 
--iter;    // iter now points to the last element 
r.erase(iter);  // pop() 

- 編輯 -

如果什麼「最後」的語義是不是插入的順序,但你ordered_non_unique索引的順序,你可以用「reverse_iterator的::基地()」,這給了一個向前的'迭代器'到下一個元素:

RequestsContainer r; 
/* ... fill r ... */ 
auto index = r.get<1>();  // or get<0> if no sequenced<> 
auto riter = index.rbegin(); // reverse_iterator 
++riter;      // points previous to last element 
auto iter = riter.base(); // points to the last element 
r.erase(iter);    // pop() 

另請參閱this有關將逆向迭代器轉換爲向前迭代器的答案。

+0

謝謝,但我需要使用ordered_non_unique索引刪除最後一個項目。在你的解決方案中,我會刪除最後一項,保持插入順序。我對嗎? – user2301299 2013-04-25 02:02:10

+1

是的,你是對的,我不明白你的問題。我正在使用reverse_iterator :: base()更新我的答案,這正是你想要的。 – Antoine 2013-04-25 08:38:23

相關問題