Avoiding iterator invalidation using indices, maintaining clean interface

前端 未结 4 706
悲&欢浪女
悲&欢浪女 2021-02-02 02:24

I have created a MemoryManager class which is basically a wrapper around two vectors of pointers that manage lifetime of heap-allocated objects.

O

4条回答
  •  旧巷少年郎
    2021-02-02 03:05

    You can implement your own iterator class.

    Something like the following may help.

    template 
    class IndexIterator : public std::iterator
    {
    public:
        IndexIterator(std::vector& v, std::size_t index) : v(&v), index(index) {}
    
        // if needed.
        typename std::vector::iterator getRegularIterator() const { return v->begin() + index; }
    
        T& operator *() const { return v->at(index); }
        T* operator ->() const { return &v->at(index); }
    
        IndexIterator& operator ++() { ++index; return *this;}
        IndexIterator& operator ++(int) { IndexIterator old(*this); ++*this; return old;}
        IndexIterator& operator +=(std::ptrdiff_t offset) { index += offset; return *this;}
        IndexIterator operator +(std::ptrdiff_t offset) const { IndexIterator res (*this); res += offset; return res;}
    
        IndexIterator& operator --() { --index; return *this;}
        IndexIterator& operator --(int) { IndexIterator old(*this); --*this; return old;}
        IndexIterator& operator -=(std::ptrdiff_t offset) { index -= offset; return *this;}
        IndexIterator operator -(std::ptrdiff_t offset) const { IndexIterator res (*this); res -= offset; return res;}
    
        std::ptrdiff_t operator -(const IndexIterator& rhs) const { assert(v == rhs.v); return index - rhs.index; }
    
        bool operator == (const IndexIterator& rhs) const { assert(v == rhs.v); return index == rhs.index; }
        bool operator != (const IndexIterator& rhs) const { return !(*this == rhs); }
    
    private:
        std::vector* v;
        std::size_t index;
    };
    
    template 
    IndexIterator IndexIteratorBegin(std::vector& v)
    {
        return IndexIterator(v, 0);
    }
    
    template 
    IndexIterator IndexIteratorEnd(std::vector& v)
    {
        return IndexIterator(v, v.size());
    }
    

提交回复
热议问题