使用向量和指针的双下标重载的区别
Difference of double subscript overloading between using vector and pointer
我正试图通过使用向量和指针来重载[][]。事实上,我成功地对它们进行了编码。但我对矢量版本有点困惑。请参考我的实现如下:
这是指针版本:
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;
};
当然,你成功的矢量版本会更好。
相关文章:
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 运算符重载多个任务的下标和赋值运算符
- 允许 nullptr 的 C++ 重载下标取消引用
- 基成员的重载下标运算符
- 如何重载下标运算符以返回可以是左值的可选值?
- 如何从重载的下标 [] 运算符返回 std::unique_ptr&?
- 重载下标运算符不返回指针
- 如何在复制构造函数中调用重载的下标
- 如何通过指针简化重载下标运算符的使用
- 重载赋值运算符带下标运算符
- 下标赋值重载
- 将 boost::shared_ptr 与重载下标运算符 ([]) 的类一起使用
- 重载下标运算符以根据分配的类型调用函数
- 从重载的下标运算符调用虚函数
- C++双下标运算符重载
- 在 C++ 中重载双下标运算符 [][]
- 重载下标运算符会导致访问冲突
- 使用向量和指针的双下标重载的区别
- 使用类模板初始化下标重载函数中的引用类型无效
- 使用下标重载的单链表排序