我想为通用2D数组创建自己的类。这就是我到目前为止所做的:
#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; }
};
因为我的类有我自己的[]
运算符,它返回vector<T>
,它可以被向量类的默认[]
运算符访问,我希望我的class会像普通向量一样工作,但似乎并非如此。以下显示了我如何能够或不能更改2D数组元素的三种方法:
My2DArray<int> intArray1(5, 5);
intArray1[0][0] = 2; //does not work
cout << intArray1[0][0] << "\n"; //prints 0
/*-------------------------------------------*/
My2DArray<int> intArray2(5, 5);
*intArray2.at(0,0) = 2; //works
cout << intArray2[0][0] << "\n"; //prints 2
/*-------------------------------------------*/
vector<vector<int>> intArray3;
intArray3.resize(5);
for (int i = 0; i < 5; i++) {
intArray3[i].resize(5);
}
intArray3[0][0] = 2; //works
cout << intArray3[0][0] << "\n"; //prints 2
有没有办法让[][]
运算符为我自己的类工作,还是我需要使用我的.at(x,y)
函数给我一个指针并用它来修改一个值?
答案 0 :(得分:3)
您的operator[]
会返回矩阵列的新副本,效率非常低,不允许修改矩阵。如果要访问实际矩阵元素,请将方法的返回类型更改为引用:
vector<T> &operator[](size_t index) {
return array[index];
}
(size_t
更有意义,因为索引的类型可能不需要负指数。)
My2DArray(size_t w, size_t h) : width(w), height(h), array(w, vector<T>(h)) {}
而不是第一次默认构造,然后在ctor体中另外更改。