调整方法 intArray

Resize method intArray

我正在为大学编写 IntArray class,但不知道如何有效地编写我的 resize 方法。我所拥有的不支持调整为较小的列表,我不知道如何解决这个问题..

这是我的代码:

 void IntArray::resize(unsigned int size){
     for (int i = size;i<length;i++){
         data[i] = 0;
     }
     length = size;
 }

头文件

#ifndef INTARRAY_H_
#define INTARRAY_H_

#include <iostream>
using namespace std;

class IntArray{
private:
     int length;
     int * data;
public:
    IntArray(int size = 0);
    IntArray(const IntArray& other);
    IntArray& operator=(const IntArray& original);

    int getSize() const { return length; };
    int& operator[](unsigned int i);
    void resize(unsigned int size);
    void insertBefore(int value, int index);

    friend ostream& operator<<(ostream& out, const IntArray& list);
    ~IntArray(){ delete[] data; };
};

当您需要调整大小时,您实际上是要创建一个新数组,将旧数组复制到新数组中,然后删除旧数组。

 void IntArray::resize(unsigned int size){
     if (size <= length)  // if we are making it smaller reset the size and do nothnig
     {
        my_size = size
        return;
     }
     int * temparr = new int[size];
     // copy data
     for (unsigned int i = 0; i < length; ++i)
        temparr[i] = data[i];
     delete [] data; // get rid of the old array
     data = temparr; // set data to the new array
     length = size; // set the new size
 }

您还应该有一个 capacity 成员,它像 std::vector 一样跟踪数组的实际大小。这样你就可以拥有一个比你需要的更大的数组,因为它的增长需要更少的重新分配。