gpt4 book ai didi

c++ - multi_index_container 删除最后一个元素

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:50:46 26 4
gpt4 key购买 nike

我有以下定义:

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;

我需要从这个容器中移除(弹出)最后一个元素。我怎样才能做到这一点? reverse_iterator 不能与 erase() 一起使用。

谢谢

最佳答案

使用 'sequenced<>' 索引你会得到类似于 'std::list' 的语义,参见 codumentationcode example从 boost 。将您的“typedef”更改为:

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::list”的额外语义,你得到一个双向迭代器到最后并按照 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()

-- 编辑--

如果“last”的语义不是插入顺序而是 ordered_non_unique 索引的顺序,您可以使用“reverse_iterator::base()”,它为下一个元素提供前向“迭代器”:

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回答关于将反向迭代器转换为正向迭代器的问题。

关于c++ - multi_index_container 删除最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16190314/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com