简体   繁体   中英

Vector Template Class: erase(iterator begin, iterator end)

So I am trying to implement a vector template class and I am trying to write an erase function. The erase function takes two iterators, start and end . It then erases every element from position start to end including start , but not end . After it erases the range of elements it shifts the elements left so that there are no empty elements in the middle of the array (I can try and explain better if this is not clear enough).

The private member data for the class is an integer called Size , which stores the current number of elements in the array, an integer called Capacity which stores the current space allocated for the array, and an array called Arr . I'm not great with iterators yet, can someone explain to me how I can do this better or how to fix it?

template <typename T>
typename Vector<T>::iterator Vector<T>::erase(iterator start, iterator end)
{
    iterator x = start;

    for(; x != end; x++)
    {
        Arr[x].~T();
    }

    for(iterator x = start; x < theSize - (start - end); x++)
    {
        Arr[x] = Arr[x + (start - end)]; 
    }

    Size -= end - start;      

}

You cannot destroy objects in the middle of the vector, and then assign to them. You can only assign to "live" objects.

What you could do is (move)assign members from [end-iterator, vector::end()) over the start and following element. And then destroy excess objecs at the end of the vector.

Here is an example using the real std::vector interface with const_iterator for the erased range:

  iterator erase(const_iterator _First, const_iterator _Last)
  {
     const size_type _Offset = _First - cbegin();
     const size_type _LastOffset = _Last - cbegin();

     iterator _NewEnd = std::move(begin() + _LastOffset, end(), begin() + _Offset);
     _DestroyData(_NewEnd, end());
     _SetSize(_NewEnd - begin());

     return begin() + _Offset;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM