我该如何实现擦除方法?

时间:2011-05-08 22:12:27

标签: c++ vector erase

void reserve( int newCapacity ){
     Object *oldArray = objects;
     int numToCopy = newCapacity < theSize ? newCapacity : theSize;
     newCapacity += SPARE_CAPACITY;
     objects = new Object[newCapacity];
     for( int k=0; k < numToCopy; k++ )
         objects[k] = oldArray[k];
     theSize = numToCopy;
     theCapacity = newCapacity;
     delete [ ] oldArray;
}

我如何实现擦除方法,可能使用reserve()?

iterator erase ( iterator position ){
    if (position + 1 != end())
       copy(position + 1, finish, position);
    --finish;
    return position;
}

1 个答案:

答案 0 :(得分:3)

似乎应该这样做:

iterator erase ( iterator position ) {
  copy(position+1, end(), position);
  resize(size()-1);
  return position;
}
iterator erase ( iterator first, iterator last ) {
  copy(last, end(), first);
  resize(size()-(last-first);
  return first;
}