简体   繁体   中英

How would one write a custom Vector method to delete an element without using vector::erase()?

I'm writing a custom vector class, and I need to have an erase function without actually using vector::erase();

I need the same functionality, using only what I can write along with a few other pre-completed methods such as resize(), reserve(), pop, and push_back. The only parameter it takes is an iterator. My vector specifically is holding a bunch of lists. The element pointed to by the iterator should be deleted, and the rest of the vector left the same.

Here are some of the methods I have already:


void resize( int newSize )
    {
        if( newSize > theCapacity )
            reserve( newSize * 2 );
        theSize = newSize;
    }

    void reserve( int newCapacity )
    {
        if( newCapacity < theSize )
            return;

        Object *newArray = new Object[ newCapacity ];
        for( int k = 0; k < theSize; ++k )
            newArray[ k ] = std::move( objects[ k ] );

        theCapacity = newCapacity;
        std::swap( objects, newArray );
        delete [ ] newArray;
    }

      // Stacky stuff
    void push_back( const Object & x )
    {
        if( theSize == theCapacity )
            reserve( 2 * theCapacity + 1 );
        objects[ theSize++ ] = x;
    }
      // Stacky stuff
    void push_back( Object && x )
    {
        if( theSize == theCapacity )
            reserve( 2 * theCapacity + 1 );
        objects[ theSize++ ] = std::move( x );
    }

    void pop_back( )
    {
        if( empty( ) )
            throw UnderflowException{ };
        --theSize;
    }

Is such a thing possible?

Typically std::vector::erase manually calls the dtor, uses placement new to copy construct (or move construct, if available) the elements into that gap, and then modifies the end iterator.

A simple implementation with iterators:

void erase(Iterator<Object> it) {
    while (next(it) != end()) {
        *it = *next(it); // or std::move(*next(it))
        it  =  next(it);
    }
    --theSize;
    end()->Object::~Object(); // not necessary -- assumes updated end()
}

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