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

Pass pointer to data as argument to function expecting two-dimensional array

本文关键字:参数传递 期望 函数 二维数组 数据 指针      更新时间:2023-10-16

>请考虑以下代码

#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

使用 C 样式转换

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

或者如果您想键入更多内容,请使用reinterpret_cast

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