将指向数据的指针作为参数传递给期望二维数组的函数

时间:2013-10-13 20:31:18

标签: c++

考虑以下代码

#include<algorithm>
#include<iostream>
#include<array>

void show(double x[2][2]) {
  std::cout<<x[0][0]<<", "<<x[0][1]<<std::endl
           <<x[1][0]<<", "<<x[1][1]<<std::endl;
}

int main() {
  std::array<double, 4> y = {1, 2, 3, 4};  
  double x[2][2];

  // it is safe to copy because x[2][2] consists of
  // four contiguous blocks of memory in row-major order

  std::copy(y.begin(), y.end(), &x[0][0]);

  show(x); // this, obviously, works as expected

  // but how can I cast y, or y.data(),
  // or y.begin() to use the function foo?    
  // show(y); 
}

我正在使用遗留库,其中许多函数参数类似于x[a][b]。但是,我的代码依赖于线性数据表示(也就是说,我只使用C ++“线性”容器,例如std::array<T, N>)。

想象一下,经过费力的计算后,我已经在std::array<double, 2>包含我需要的数据的代码中达到了一个点,现在我需要对该数据调用foo

我如何“强制转换”(因为没有更好的词)底层容器,以便我可以调用期望double[2][2]的遗留函数?

我真的不想复制(如示例所示),因为foo等遗留函数被称为数十万次。

作为一个极端的优点,我想将这些遗留函数包装在类似C ++算法的接口之后;类似的东西:

std::vector<std::array<double, 4>> z;
fooify(z.begin(), z.end()); // calls foo(zi) for each zi in z

编辑:一些答案

感谢@ 6502,我开始提出一个解决方案:

#include<algorithm>
#include<iostream>
#include<array>

namespace legacy {
void show(double x[2][2]) {
  std::cout<<x[0][0]<<", "<<x[0][1]<<std::endl
           <<x[1][0]<<", "<<x[1][1]<<std::endl;
}
}

template<size_t N, typename Container>
void show(Container& y) {
  return legacy::show(reinterpret_cast<double(*)[N]>(y.data()));
}

int main() {
  std::array<double, 4> y = {1, 2, 3, 4};  
  show<2>(y);
}

按预期工作 - 当然,我可以自动推断出“重塑”因素(在这种情况下它是2,但在一般情况下会有所不同)。

然后我会尝试将这个“重构”函数合并到算法中。

为了完整起见,我添加了编译细节(OS X 10.7.4使用GCC 4.8.1):

$ g++ example.cpp -std=c++11 -Wall -Wextra
$ ./a.out                                                 
1, 2
3, 4

1 个答案:

答案 0 :(得分:3)

使用C风格的演员

show((double (*)[2])y.data());

或使用reinterpret_cast如果您想输入更多

show(reinterpret_cast<double (*)[2]>(y.data()));
相关问题