C++ - 需要传递二维数组,但必须动态调整大小

标签 c++ arrays dynamic

我正在使用一个 C++ 库,它要求我向它传递一个二维数组。他们的代码示例给出了一个静态大小的数组,如下所示:

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”时感到困惑。

如果我无法更改此库(它是第 3 方),我该如何向它传递动态大小的数据?

谢谢, 麦迪。

最佳答案

可能 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 的工作原理。

但如果我的猜测是正确的,这会有所帮助。

关于C++ - 需要传递二维数组,但必须动态调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14146756/

相关文章:

c++ - 为刚刚声明的类定义 STL 容器。

c++ - 使用 QT 和 MinGW32 在 Windows 上检查内存泄漏

c# - 如何在 C# 中对动态列表进行排序

database - PostgreSQL 在不动态编写 SQL 的情况下执行多个动态 WHERE 条件

php - 我需要帮助完成这个 3 级动态下拉列表

c++ - VS 2017 不会隐式地将 const char* 转换为 char*

c++ - 使用指针

c# - 读取 CSV 文件并将值存储到数组中

python - 在 Python 3 中向数组添加坐标

python - Numpy searchsorted降序