2

I have following definition:

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;

I need to remove (pop) last element from this container. How can I do this? reverse_iterator cannot be used with erase().

Thank you

user2301299
  • 529
  • 1
  • 5
  • 15

1 Answers1

2

Using the 'sequenced<>' index you get semantics similar to 'std::list' see the codumentation and code example from boost. Change your 'typedef' to:

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;

And then, having the additional semantics of a 'std::list', you get a bidirectional iterator to the end and decrement it as per this question, like that:

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()

-- EDIT --

if what the semantics for "last" isn't the order of insertion but the order of your ordered_non_unique index, you can use 'reverse_iterator::base()' which gives a forward 'iterator' to the next element:

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()

See also this answer about converting reverse iterator to forward iterators.

Community
  • 1
  • 1
Antoine
  • 13,494
  • 6
  • 40
  • 52
  • Thank you but I need to remove last item using ordered_non_unique index. In your solution I would remove last item, keeping order of insertion. Am I right? – user2301299 Apr 25 '13 at 02:02
  • 1
    Yes, you are right, I didn't understand that from your question. I'm updating my answer using reverse_iterator::base() which is what you want. – Antoine Apr 25 '13 at 08:38