加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:06:45 所属栏目:百科 来源:网络整理
导读:请考虑以下代码 #includealgorithm#includeiostream#includearrayvoid show(double x[2][2]) { std::coutx[0][0]","x[0][1]std::endl x[1][0]","x[1][1]std::endl;}int main() { std::arraydouble,4 y = {1,2,3,4}; double x[2][2]; // it is safe to copy b
请考虑以下代码
#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.

如何“强制转换”(因为缺少一个更好的词)底层容器,以便我可以调用期望双[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[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};  
  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()));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读