如何在不使用 vector::erase() 的情况下编写自定义 Vector 方法来删除元素?



我正在编写一个自定义向量类,我需要有一个擦除函数而不实际使用 vector::erase((;

我需要相同的功能,只使用我能写的内容以及其他一些预先完成的方法,如 resize((、reserve((、pop 和 push_back。它采用的唯一参数是迭代器。我的矢量特别包含一堆列表。迭代器指向的元素应删除,矢量的其余部分保持不变。

以下是我已经拥有的一些方法:


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;
}

这样的事情可能吗?

通常 std::vector::erase 手动调用 dtor,使用放置 new 将构造(或移动构造,如果可用(元素复制到该间隙中,然后修改结束迭代器。

使用迭代器的简单实现:

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()
}

相关内容

最新更新