我正在嘗試獲取此矩陣并將其列印在另一個函式中。問題是這是不可能的。我試圖用 ** 和 * 解決它,但我只得到地址而不是值,但我無法得到矩陣 5x5 中的正常值。有人可以向我解釋我做錯了什么嗎?
size_t matrix[5][5] =
{
{1, 16, 20, 23, 25},
{6, 2, 17, 21, 24},
{10, 7, 3, 18, 22},
{13, 11, 8, 4, 19},
{15, 14, 12, 9, 5},
};
set<bool> set1 = iterateover((size_t**)matrix)
std::set<bool> iterateover(size_t** array)
size_t numberofrows = sizeof(**arrayy) / sizeof(arrayy[0]);
size_t numberofkols = sizeof(*arrayy[0]) / sizeof(arrayy[0][0]);
std::set < bool >myset;
for (size_t i = 0; i < numberofrows; i )
{
for (size_t j = 0; j < numberofkols; j )
{
std::cout << arrayy[i][j] << std::endl;
return myset;
uj5u.com熱心網友回復:
你得到的行,列號不正確,應該是這樣的:
size_t numberofrows =
sizeof(matrix) / sizeof(matrix[0]);
size_t numberofcols = sizeof(matrix[0]) / sizeof(matrix[0][0]);
并且您想列印到其他功能讓我們使用模板
template <typename T>
void print_matrix(T matrix, int numberofcols, int numberofrows)
{
for (size_t i = 0; i < numberofrows; i ) {
for (size_t j = 0; j < numberofcols; j ) {
std::cout << matrix[i][j] <<" ";
}
std::cout << "\n";
}
}
測驗于:https ://godbolt.org/z/vshev1e17
uj5u.com熱心網友回復:
如果你想在 fun 中定義它并在另一個函式中列印它你需要動態而不是靜態的,或者你可以全域定義它并從你定義的任何函式訪問它檢查這個從函式回傳一個二維陣列
uj5u.com熱心網友回復:
您可以制作iteratreOver一個可以通過參考獲取二維陣列的函式模板,如下所示。
#include <iostream>
template<typename T,std::size_t N, std::size_t M>
void iterateOver(T (&arr)[N][M])
{
for(std::size_t i= 0; i < N; i)
{
for(std::size_t j = 0; j < M; j)
{
std::cout<<arr[i][j] <<" ";
}
std::cout<<std::endl;
}
}
int main()
{
size_t matrix[5][5] =
{
{1, 16, 20, 23, 25},
{6, 2, 17, 21, 24},
{10, 7, 3, 18, 22},
{13, 11, 8, 4, 19},
{15, 14, 12, 9, 5},
};
//call iterateOver by passing the matrix by reference
iterateOver(matrix);
}
上述程式的輸出可以在這里看到:
1 16 20 23 25
6 2 17 21 24
10 7 3 18 22
13 11 8 4 19
15 14 12 9 5
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441472.html
