簡體   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