Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用[][]运算符更改常规二维数组类的值_C++_Arrays_Generics_Vector - Fatal编程技术网

C++ 使用[][]运算符更改常规二维数组类的值

C++ 使用[][]运算符更改常规二维数组类的值,c++,arrays,generics,vector,C++,Arrays,Generics,Vector,我想为通用二维数组创建自己的类。这就是我到目前为止所做的: #pragma once #include <vector> using namespace std; template<class T> class My2DArray { private: vector<vector<T>> array; int width, height; public: My2DArray() {} My2DArray(in

我想为通用二维数组创建自己的类。这就是我到目前为止所做的:

#pragma once
#include <vector>

using namespace std;

template<class T> 
class My2DArray {
private:
    vector<vector<T>> array;
    int width, height;

public:
    My2DArray() {}
    My2DArray(int w, int h) : width(w), height(h) {
        array.resize(w);
        for (int i = 0; i < w; i++) {
            array[i].resize(h);
        }
    }

    ~My2DArray() {}

    vector<T> operator[](int index) {
        return array[index];
    }

    T* at(int x, int y) {
        return &array[x][y];
    }

    int getWidth() { return width; }
    int getHeight() { return height; }
};

有没有办法让
[]]
操作符为我自己的类工作,或者我需要使用我的
.at(x,y)
函数给我一个指针并使用它来修改值?

你的
操作符[]
返回矩阵列的新副本,效率很低,不允许修改矩阵。如果要访问实矩阵元素,请将方法的返回类型更改为引用:

vector<T> &operator[](size_t index) {
    return array[index];
}

而不是先构造默认值,然后在ctor正文中另外更改。

您的
运算符[]
返回矩阵列的新副本,效率非常低,不允许修改矩阵。如果要访问实矩阵元素,请将方法的返回类型更改为引用:

vector<T> &operator[](size_t index) {
    return array[index];
}

而不是构造第一个默认值,然后在ctor正文中另外更改。

您缺少了第二个重载的
运算符[]
,该重载将允许
const My2DArray
能够使用
[]
。此外,在这种情况下,您不应该使用诸如
width
height
等无关变量。您使用的是
向量
,而
向量
通过调用
size()
方法知道其维度。通过使用这些无关的变量,您增加了错误发生的可能性(因为没有更新宽度和高度变量)。因此,您的构造函数可以是:
My2DArray(intw,inth):没有任何循环的数组(w,std::vector(h)){}
。此外,在这种情况下,您不应该使用诸如
width
height
等无关变量。您使用的是
向量
,而
向量
通过调用
size()
方法知道其维度。通过使用这些无关的变量,您增加了错误发生的可能性(因为没有更新宽度和高度变量)。因此,您的构造函数可以是:
My2DArray(intw,inth):没有任何循环的数组(w,std::vector(h)){}
My2DArray(size_t w, size_t h) : width(w), height(h), array(w, vector<T>(h)) {}