ArrayVector类的运算符[]重载

Overloading operator[] for ArrayVector class

本文关键字:重载 运算符 ArrayVector      更新时间:2023-10-16

嗨,我在写这个函数时遇到问题:

int& ArrayVector::operator[](int index)

它必须执行以下

返回对数组的索引第th个元素的引用

如果索引大于或等于数组的大小,1.将数组扩展到(索引+1)元素2.将元素从旧数组复制到扩展数组3.为从第n个到第(索引-1)个的元素填充04.返回索引第th个元素还要跟踪阵列的大小到目前为止,这是我的课。我只需要这个功能的帮助。谢谢

class ArrayVector {
private:
  int* data;
  int n;
public:
  ArrayVector() : data(NULL), n(0) { }
  int size() const {
    return n;
  }
  // print content of the array separated by “ “
  void print() {
    if (n == 0)
      return;
    // print from first element to second last element
    for (int i = 0; i < n-1; ++i)
      cout << data[i] << " ";
    // print last element
    cout << data[n-1] << endl;
  }
  // Return reference to index-th element of the array
  //  If index is greater or equal to size of the array,
  //    1. expand the array to cover up to (index+1) 
  //    elements
  //    2. copy elements from old array to expanded array
  //    3. fill 0 for elements from n-th to (index-1)-th
  //    4. return the index-th element
  //  Also keep track the size of the array
  int& operator[](const int index);
};
 

int& ArrayVector::operator[](int index) {
  // TODO
}

如果索引在范围内,只需返回元素。其他:将大小为(n+(n-index+1))的新数组分配到临时指针中。使用for循环复制前"n"个值。将0放入新数组的其余部分。将"n"设置为新大小,删除旧的已分配数组。将"data"设置为指向新数据。返回元素。

您的operator[]可以如下所示:

int& ArrayVector::operator[](int index)
{
    if(index > 0 && index < n)
        return data[index];                // if index is in range, just return an element
    else{                                  // if not, 
        int *nData = new int[index+1];     // create a new, temporarily array with size index+1
        for(int i = 0; i < n; i++)
            nData[i] = data[i];            // copy data to our new aray
        delete[] data;                     // delete our old array
        for(int i = n; i < index+1; i++)
            nData[i] = 0;                  // fill newly created elements with 0
        data = nData;                      // set data to point to our new created array
        n = index+1;                       // set new data size
        return data[index];                    // return element with that index
    }
}

您可以拥有这个

int& operator[](const int index){
    if(index>0 && index<n){
       return data[index];
    }
    else if(index>n){
      int *newData = new int[index+1];
      for(int i=0;i<n;i++){
          newData[i]=data[i];
      }
      for(int i=n;i<index+1;i++){
          newData[i]=0;
      }
      return newData[index];
    }else{
      return;
    }

};