使用向量和指针的双下标重载的区别

Difference of double subscript overloading between using vector and pointer

本文关键字:下标 重载 区别 指针 向量      更新时间:2023-10-16

我正试图通过使用向量和指针来重载[][]。事实上,我成功地对它们进行了编码。但我对矢量版本有点困惑。请参考我的实现如下:

这是指针版本:

class Array2 {
    private:
    unsigned row, col;
    int** arr;
    public:
    Array2(unsigned r=0, unsigned c=0): row(r), col(c) {
        if(row * col != 0) {
            arr = new int*[row];
            for(int i = 0; i < row; i++) {
                arr[i] = new int[col];
            }
        }
    }
    class Proxy {
    public:
        Proxy(int* _array) : _array(_array) { }
        int& operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };
    Proxy operator [] (int index) {
        return Proxy(arr[index]);
    }
}

这是矢量版本:

class Array2 {
    private:
        unsigned row, col;
        vector<vector<int> > arr;
    public:
        Array2(unsigned r=0, unsigned c=0)
            : row(r), col(c), arr(r, vector<int>(c)) { }
    vector<int>& operator [] (int index) {
        return arr[index];
    }
}

这是失败矢量版本:

class Array2 {
    private:
        unsigned row, col;
        vector<vector<int> > arr;
    public:
        Array2(unsigned r=0, unsigned c=0)
            : row(r), col(c), arr(r, vector<int>(c)) { }
    class Proxy {
    public:
        Proxy(vector<int> _array) : _array(_array) { }
        int& operator[](int index) {
            return _array[index];
        }
    private:
        vector<int> _array;
    };
    Proxy operator [] (int index) {
        return Proxy(arr[index]);
    }
}

对于失败版本,我无法使用arr[2][3] = 23等操作成功地为向量赋值。有人能告诉我我在失败向量版本中误解了什么吗?非常感谢。

Proxy(vector<int> _array) : _array(_array) { }时,复制vector。这意味着Proxy内的_array与原始vector(即return Proxy(arr[index]);时的arr[index])无关

您可以保存指向vector的指针。例如:

class Proxy {
public:
    Proxy(vector<int>& _array) : p(&_array) {}
    int& operator[](int index) {
        return (*p)[index];
    }
private:
    vector<int>* p;
};

当然,你成功的矢量版本会更好。