[英]Passing smart pointers to a function
我有一个双精度的二维智能指针数组。 我可以给它赋值并显示它,但是我很难将其传递给需要double **作为输入的函数。 简单的get()不起作用。
#include <iostream>
#include <memory>
using namespace std;
# define DIM1 3
# define DIM2 4
void funcCall(double** item)
{
cout<< "Test function.";
}
int main() {
std::unique_ptr<std::unique_ptr<double[]>> myArray(new std::unique_ptr<double[]>[DIM1]);
for (int i = 0; i < DIM1; i++)
{
myArray.get()[i].reset(new double[DIM2]);
}
std::cout<<"Assign values"<<std::endl;
for (int i = 0; i < DIM2; i++)
{
for (int j = 0; j < DIM1; j++)
{
myArray.get()[j][i] = (j+1)*(i+1);
}
}
funcCall(myArray.get());
return 0;
}
编译时,我得到:
error: cannot convert 'std::unique_ptr<std::unique_ptr<double []> >::pointer {aka std::unique_ptr<double []>*}' to 'double**' for argument '1' to 'void funcCall(double**)' funcCall(myArray.get())
调用的类型和函数标头不匹配。 您不能将unique_ptr视为常规指针。
一种解决方案是将函数定义更改为:
void funcCall(std::unique_ptr<double[]> *item)
void funcCall(std::unique_ptr<std::unique_ptr<double[]>> & arr)
应该做你想做的,但是...
听起来您正在尝试重新发明轮子。 不要那样做 除非这是用于任务或个人教育,否则会发疯。
而是使用内置容器之一。
由于DIM1
和DIM2
是不变的,你可以使用
std::array<std::array<double, DIM2>,DIM1> myArray;
和
void funcCall(std::array<std::array<double, DIM2>,DIM1> arr)
但是您想要一个动态解决方案的可能性非常大。 在这种情况下,请尝试
std::vector<std::vector<double>> myArray(DIM1, std::vector<double>(DIM2));
和
void funcCall(std::vector<std::vector<double>> arr)
老实说,这是一个傻瓜下注。 数组的数组或向量的向量在内存中不连续,因此计算机必须在存储中四处走动,从而将时间浪费在不必要的缓存未命中上,并且加载和可能重新加载缓存所花费的时间通常比所涉及的计算要长。 目前,世界上所有133t数学都无法为您提供帮助,因为您已受到IO的限制,而IO就是sssssssssllllloooowwwwwwww。
您真正想要的是一个手动索引的漂亮的一维数组。 行*列数+列。 当然,手动索引看起来像是额外的工作,但请停下来想一想:编译器在后台做了多少数学运算,以使您可以数组工作,hmmm? 大概差不多。 您只是看不到它。
现在让我们停留在std :: vector上,但同样适用于std :: array甚至是一个好的静态数组或智能指针内部的动态数组。
std::vector<double> myArray(DIM1*DIM2);
使用这个相对简单:
myArray[row*DIM2 + column];
该函数是:
void funcCall(std::vector<double> arr)
但这很容易包装在一个类中并进一步简化:
class matrix
{
private:
std::vector<double> myArray;
size_t nrRows;
size_t nrColumns;
public:
matrix(size_t rows, size_t columns):
myArray(rows*columns), nrRows(rows), nrColumns(columns)
{
}
double& operator()(size_t row, size_t column)
{
return myArray[row* nrColumns + column];
}
double operator()(size_t row, size_t column) const
{
return myArray[row* nrColumns + column];
}
};
施工:
matrix mat(DIM1, DIM2);
和用法:
double d = mat(1,2);
要么
mat(2,1) = 3.14;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.