我的重载 [] 运算符不适用于伪 3D 数组
My overloaded [] operator does not work for a pseudo 3D array
我写了一个小演示,它应该实现三维std::vector
的伪[][][] operator
。目的是调用[] operator
,直到只返回类型 T。不幸的是,程序似乎崩溃了,运算符被递归调用。
#include <vector>
#include <iostream>
template <class T>
class V1D : public std::vector<T>
{
private:
int _iX = 0;
int _iBeg = 0;
public:
V1D(int x, int beg, std::vector<T> &buf)
: _iX(x)
{
this->swap(buf);
_iBeg = beg;
}
T& operator[] (int id) {
return (*this)[id + _iBeg];
}
};
template <class T>
class V2D : public std::vector<T>
{
private:
int _iX = 0;
int _iY = 0;
int _iBeg = 0;
public:
V2D(int x, int y)
: _iX(x)
, _iY(y)
{
this->resize(_iX*_iY);
}
V2D(int x, int y, int beg, std::vector<T> &buf)
: _iX(x)
, _iY(y)
{
this->swap(buf);
_iBeg = beg;
}
V1D<T> operator[] (int id) {
int iBeg = id*_iX;
return V1D<T>(_iX, iBeg+_iBeg, *this);
}
};
template <class T>
class V3D : public std::vector<T>
{
private:
int _iX = 0;
int _iY = 0;
int _iZ = 0;
public:
V3D() = default;
V3D(int x, int y, int z)
: _iX(x)
, _iY(y)
, _iZ(z)
{
this->resize(_iX*_iY*_iZ);
}
V2D<T> operator[] (int id) {
int iBeg = id*_iY*_iZ;
return V2D<T>(_iY, _iZ, iBeg, *this);
}
};
int main()
{
V3D<float> v3(3, 3, 3);
float v = v3[1][1][0];
v3[1][1][0] = 5;
v = v3[1][1][0];
std::cout << v << std::endl;
}
我不认为在 V1D 和 V2D 构造函数(可能应该是私有的)中这样做>swap(buf) 是一个好主意。如果你考虑一下,V3D::operator[] 将临时(它作为结果返回)中的空向量与变量中的任何内容交换。所以你失去了内容。这种设计将不起作用。您可能需要返回一个指针,指向包装在帮助程序类中的 vector 数据。
V1D 和 V2D 不应该也不需要保持/成为载体。它们应该包裹普通的 T 指针,可能带有内部尺寸。
你递
归地调用operator[]
T& operator[] (int id) {
return (*this)[id + _iBeg];
}
应该是
T& operator[] (int id) {
return std::vector<T>::operator[](id + _iBeg);
}
相关文章:
- FLTK 2.0构建和演示,适用于VS2019的2011年左右的代码库
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- 适用于 WebView2 旧版本的示例应用程序
- 在 NVIDIA GEFORCE GTX 1050 上下载适用于 Windows 10 的 openCL 1.2
- __attribute__(优化(0))) 是否适用于"recursively"?
- 为什么 std::erase(std::erase_if) 不是适用于<algorithm>任何容器的模板?
- 使用一个参数的模板函数时出错(适用于 2)
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 为什么这适用于 G++ 而不是 CLANG?
- 适用于 macOS 的 Xcode 应用程序。这就是我设置从USB麦克风输入获取音频的方式。一年前工作,现在没有了。为什么
- 适用于 Linux 的 c++ 上的代理脚本
- 为什么我的 SFINAE 表达式不再适用于 GCC 8.2?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 有没有适用于Windows.lib文件的GNU二进制文件描述符(BFD)
- 模板函数仅适用于VS
- 如何在cmake中包含适用于g++或viceversa的库
- 适用于win32、linux、mac的POSIX C包装器
- WinDBG适用于从Visual Studio 2015保存的转储,但不适用于任务管理器。显示异常代码"not found"
- 从uint8_t到NPY_UINT16 PyArray_SimpleNewFromData.适用于Linux,但不适用于