vendredi 14 juillet 2017

How is std::erase implemented for vectors?

I have written a custom Vec class, duplicating the functionality of std::vector, but I am struggling to implement an erase function elegantly and which takes the same parameters as the standard library implementation. Specifically, in C++11, vector::erase has the signature iterator erase (const_iterator position);, where the returned iterator points to the new position of the element after the element deleted. My only solution was to pass a non-const iterator, copy all the elements after the given iterator back one position, and use a third iterator to store the original pointer position. This requires three non-const iterator.

template <class T> typename Vec<T>::iterator Vec<T>::erase(iterator it)
{
    iterator _it = it;

    iterator __it = it;

    while (it != (this -> end() - 1)) {
        *_it++ = *++it;
    }

    alloc.destroy(it);

    avail = it;

    return __it;
}

Here avail is the iterator which points one past the end of the vector, i.e. iterator end() { return avail; }. I don't see how any such function could take a const_iterator if it has to shift every element left by one, and I really don't like having three iterators. Is there a better solution?

Aucun commentaire:

Enregistrer un commentaire