如何使我的resize函数包含前一个向量的元素?



如何使我的resize函数包含前一个向量的元素?这基本上是模仿vector,我已经创建了push_backpop_back函数。

我还创建了一个resize函数,它将大小加倍,一个resize函数将大小减半。是否有可能在调整大小的向量中包含前一个向量的元素?

我创建的函数是resize, push_back, pop_offcopy。我能够在resize函数中复制之前的矢量元素,但是所有其他元素都是这样的:-192828272,所以它目前只是将元素设置为零。

见下面的函数。

//1/2 the array size
template <class T>
T SimpleVector<T>::resizeDwn( ){
    // decrease the size
    arraySize /= 2;
   // Allocate memory for the array.
   aptr = new T [arraySize];
   if (aptr == 0)
      memError();
   // Set the elements to zero
  for (int count = 0; count < arraySize; count++){
      aptr[count] = 0; 
  }
  // Return the array
   return *aptr;
}
//Double the array size
template <class T>
T SimpleVector<T>::resizeUp( ){
    // Increase the size
    arraySize *= 2;
   // Allocate memory for the array.
   aptr = new T [arraySize];
   if (aptr == 0)
      memError();
   // Set the elements to zero
  for (int count = 0; count < arraySize; count++){
      aptr[count] = 0; 
  }
   return *aptr;
}

程序输出

我已经尽力去做你要求我做的事了。

中没有添加绑定检查。
template <class TT>
class SimpleVector {
    TT* arr;
    int size;
public:
    SimpleVector() {}
    SimpleVector(TT n) {
        this->arr = new TT[n];
        this->size = 0;
    }
    int getLength() {
        return this->size;
    }
    void resizeUp(SimpleVector old) { // Here I have modified your resizeUp declaration
        this->size = old.getLength() * 2;
        this->arr = new TT[pointer];
        /**
         * Previous two lines are allocating the
         * array with double the size of Old SimpleVector.
         */
        for(int i = 0; i < old.getLength(); i++)
            this->arr[i] = old.arr[i];
    }
};       

请随意提问

最新更新