如何包装不使用连续内存的stl容器迭代器?前任。 std::双端队列

问题描述 投票:0回答:0

我正在编写一个自定义容器,它在内部使用 std::deque 来实现。我希望容器支持基于范围的 for 循环,因此实现了

begin()
end()
函数。我也不想将 std::deque::iterator 公开为
begin()
end()
的返回值,因此我在自定义容器中编写了自己的迭代器来返回。

我的迭代器通过指向自定义容器所保存的类型的指针进行构造,因此我可以取消引用要构造的

deque::begin()
迭代器,但我无法引用
deque::end()
,因为它是未定义的行为(尽管如果我将
deque
交换为
vector
它确实有效,但我想这是因为连续内存)。

在这种情况下如何正确包装 std::deque 以便能够正确识别容器的

end()

我可以用向量来实现这个并实现必要的

PushFront()
操作,但我认为这是一个有趣的问题。

struct Foo;

// Example custom container
class FooQueue{
public:

  FooId PushFront(Foo& foo);
  FooId PushBack(Foo& foo);
  void RemoveFoo(FooId id);

  // Custom iterator
  struct Iterator{
    using iterator_category = std::random_access_iterator_tag;
    using difference_type = std::ptrdiff_t;
    using value_type = foo;
    using pointer = value_type*;
    using reference = value_type&;

    explicit Iterator(pointer ptr) : ptr_(ptr){

    Iterator& operator++()
    {
      ptr_++;
      return *this;
    }

    Iterator operator++(int)
    {
      Iterator tmp = *this;
      ptr_++;
      return tmp;
    }

    friend bool operator==(const Iterator& lhs, const Iterator& rhs){ return lhs.ptr_ == rhs.ptr_ };
    friend bool operator!=(const Iterator& lhs, const Iterator& rhs) { return !(lhs == rhs); }
  private:
    pointer ptr_;
  };

  Iterator begin(){ return Iterator(&(*deque_.begin())); }
  Iterator end() { return Iterator(&(*deque_.end())); } /* !!! Undefined behavior: Not allowed to
  dereference .end() !!! */
private:
  std::deque<Foo*> deque_;
};

c++ iterator deque
© www.soinside.com 2019 - 2024. All rights reserved.