[英]Pass pointer to data as argument to function expecting two-dimensional array
请考虑以下代码
#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()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.