需要传递一个二维数组,但必须动态调整大小
C++ - Need to pass a 2D array, but must be dynamically sized
我正在使用一个c++库,要求我传递一个2D数组。他们的代码示例给出一个静态大小的数组,如下所示:
double data[][2] = {
{ 10, 20, },
{ 13, 16, },
{ 7, 30, },
{ 15, 34, },
{ 25, 4, },
};
但是我需要传递运行时大小的数据。所以我尝试这样做:
// unsigned numBins is passed in to this function and set at run time
double** binData = new double*[numBins];
for(unsigned i=0; i < numBins; ++i) {
binData[i] = new double[2];
}
//Set the data with something like
// binData[7][0] = 10;
// binData[7][1] = 100;
//Later, diligently delete my data...
但是,这在我使用的库中失败了。它结束了一些无用数字的图形。
我知道数组不是指针。库可能会在某个地方搞不清"sizeof"。
如果我不能改变这个库(它是第三方),我怎么去传递它动态大小的数据?
谢谢,玛迪。
可能API期望一个指针指向它所假定的二维数组的平面化表示的第一个元素。
所以简单的方法如下:
template<typename T>
struct FlatVectorAs2D {
private:
size_t width;
size_t height;
std::vector<T> flat_vec;
public:
std::vector<T>& base() { return flat_vec; }
std::vector<T> const& base() const { return flat_vec; }
size_t w() const { return width; }
size_t h() const { return height; }
T* operator[]( size_t index1 ) {
return &flat_vec[index1*height];
}
T const* operator[]( size_t index1 ) const {
return &flat_vec[index1*height];
}
FlatVectorAs2D( size_t w = 1, size_t h = 1 ):width(w), height(h) {
flat_vec.resize(w*h);
}
void resize( size_t w, size_t h ) {
width = w;
height = h;
flat_vec.resize(w*h);
}
T* raw() { return flat_vec.data(); }
T const* raw() const { return flat_vec.data(); }
};
使用:
void api_function(double* d);
int main() {
size_t width = 50;
size_t height = 100;
FlatVectorAs2D<double> buffer( width, height );
buffer[0][1] = 1.0;
api_function( buffer.raw() );
}
当然,这取决于API的工作方式。
如果我猜对了,这将会有帮助。
试试这个:
typedef double two_doubles[2];
int main()
{
two_doubles * p = new two_doubles[300];
// ...
delete[] p;
}
现在p
指向一个包含200个单位的双精度数组的第一个子数组。即,p[i]
为double[2]
, p[i][0]
、p[i][1]
为其成员元素。
(最好使用std::unique_ptr<two_doubles[]> p(new two_doubles[300]);
,忘记内存管理)
相关文章:
- 将动态分配的数组的大小调整为较小的大小C++
- 我的C++程序有问题.涉及动态调整整数数组的大小
- 通过新的后传递后创建的动态数组的错误以调整函数
- 根据内容动态调整 qwidget 和 qlayout 的大小
- Qt:如何调整QGraphicsItem以动态更改大小
- 调整动态数组大小时保留用户输入的值的问题
- 动态调整大小并填充C++中的矢量
- 如何在C++中实现可动态调整大小的堆栈
- 动态调整大小的不可调整大小的数组
- C++中数组的动态调整大小
- 根据文本动态调整控件大小
- 如何使用动态调整大小的字符串数组
- 动态调整组合框的宽度,以便可以显示整个字符串
- boost::random::discrete_distribution是否可动态调整大小
- 在QGraphicScene中动态调整视频大小
- 可动态调整大小的字符串数组C++类
- 如何动态调整QLabel/QVBoxLayout/QWidget中使用的QImage的大小
- 如何使提升::无锁::队列动态调整大小
- 如何动态调整二维矢量的大小
- 需要传递一个二维数组,但必须动态调整大小