我想在访问集合时通过删除迭代器从 boost multi-index
容器中删除一些元素。
我不确定是否涉及任何迭代器失效以及我下面的代码是否会使 first
和 last
迭代器失效。
如果下面的代码不正确,考虑下面的特定索引 (ordered_unique
) 的最佳方法是什么?
#include <iostream>
#include <stdint.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/key_extractors.hpp>
#include <boost/shared_ptr.hpp>
using namespace std;
class MyClass{
public:
MyClass(int32_t id) : id_(id) {}
int32_t id() const
{ return id_; }
private:
int32_t id_;
};
typedef boost::shared_ptr<MyClass> MyClass_ptr;
typedef boost::multi_index_container<
MyClass_ptr,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
boost::multi_index::const_mem_fun<MyClass,int32_t,&MyClass::id>
>
>
> Coll;
int main() {
Coll coll;
// ..insert some entries 'coll.insert(MyClass_ptr(new MyClass(12)));'
Coll::iterator first = coll.begin();
Coll::iterator last = coll.end();
while(first != last) {
if((*first)->id() == 3)
coll.erase(first++);
else
++first;
}
}
最佳答案
容器的 erase
返回迭代器的原因是使用该结果:
first = coll.erase(first);
那么您就不必担心底层实现如何处理 erase
或者它是否会移动元素。 (例如,在 vector
中,您的代码会在迭代中跳过一个元素)但是,documentation确实声明:
It is tempting to see random access indices as an analogue of std::vector for use in Boost.MultiIndex, but this metaphor can be misleading, as both constructs, though similar in many respects, show important semantic differences. An advantage of random access indices is that their iterators, as well as references to their elements, are stable, that is, they remain valid after any insertions or deletions.
仍然,只是看到 coll.erase(first++)
对我来说是一个标志,所以更喜欢用另一种方式来做。
关于c++ - 关于删除 boost multiindex 的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325299/