繁体   English   中英

C++:通过常量引用传递指针矩阵

[英]C++: pass matrix of pointers by const reference

我的问题有点简单而且可能很愚蠢,但是如果我有一个像int ** max这样的动态矩阵,并且我将它传递给一个函数calculateCost(int ** max, int n))

我的问题是:如何将其作为const引用传递?

不可能传递指针引用(请参阅此答案)

因为引用不是对象,所以没有引用数组,没有指向引用的指针,也没有对引用的引用:

 int& a[3]; // error int&* p; // error int& &r; // error

您可能想使用 STL 的向量来替换您拥有的每个指针。 int calculateCost(const std::vector> &max, int n);

这将允许您执行指针可以执行的所有基本运算符,但还有一些额外的东西,例如更简单的init 、 resize 和ranged_for_loops

template<typename T>
using matrix_t = std::vector<std::vector<T>>;

size_t width = 5, height = 3;
// std::vector<std::vector<int>> is the same as matrix_t<int>
matrix_t<int> my_matrix(height, std::vector<width, 0>);

这里有一些有用的链接来替换 malloc、new、delete...
-来自二维常量数组的二维向量
- unique_ptr
- shared_ptr
-make_unique
-make_shared

祝新年快乐 !

编辑:如上述评论中所述,在您的情况下使用 refs 没有用,您可以只使用 const 双指针

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM