需要传递一个二维数组,但必须动态调整大小

C++ - Need to pass a 2D array, but must be dynamically sized

本文关键字:动态 调整 二维数组 一个      更新时间:2023-10-16

我正在使用一个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]);,忘记内存管理)