| | | | | |

Implementing TVector<T> SetCapacity()

template <typename T>
int TVector<T>::SetCapacity(size_t newcapacity)
// Reserve more (or less) space for vector growth;
// this is where memory is allocated. Note that this is 
// an expensive operation and should be used judiciuosly. 
// SetCapacity() is called by SetSize() only when increased capacity
// is required. If the client needs to reduce capacity, a call must be
// made specifically to SetCapacity.
{
  if (newcapacity == 0)
  {
    delete [] content_;
    content_ = 0;
    size_ = capacity_ = 0;
    return 1;
  }
  if (newcapacity != capacity_)
  {
    T* newcontent = NewArray(newcapacity);
    if (newcontent == 0)
      return 0;
    if (size_ > newcapacity)
      size_ = newcapacity;
    for (size_t i = 0; i < size_; ++i)
    {
      newcontent[i] = content_[i];
    }
    capacity_ = newcapacity;
    delete [] content_;
    content_ = newcontent;
  }
  return 1;
} // end SetCapacity()

| | Top of Page | 5. A Generic Vector Class - 14 of 19