c++ - 关于删除 boost multiindex 的迭代器

标签 c++ iterator boost-multi-index

我想在访问集合时通过删除迭代器从 boost multi-index 容器中删除一些元素。

我不确定是否涉及任何迭代器失效以及我下面的代码是否会使 firstlast 迭代器失效。

如果下面的代码不正确,考虑下面的特定索引 (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/

相关文章:

c++ - OpenGL 是否可以同时激活两个 VAO?

c# - 与不同类中的另一个函数互操作

c++ - 调试 Opencv Android 应用程序

c++ - 在 C++ "No Matching Function"中对 vector 使用删除函数的问题

java - 为什么迭代器打印的哈希码不是实际值?

boost - 如何在不影响插入顺序的情况下替换多索引容器中的项目?

c++ - boost multi_index 是如何实现的

c++ - Windows 上 DLL Exporting/Importing 和 Extern 的问题

Java,一个集合上的多个迭代器,删除适当的子集和 ConcurrentModificationException

c++ - 如何制作一个 boost 多索引复合范围语句,相当于 where x AND y?