簡體   English   中英

C++:通過引用傳遞二維數組?

[英]c++ : pass 2d-array by reference?

我又回到了 c++ 並且在弄清楚如何將 2D 數組傳遞給函數時遇到了麻煩。 下面的代碼是我目前的嘗試,我已經能夠使用以下方法通過引用傳遞向量字符串:

vector<string> g_dictionary;
getDictionaryFromFile(g_dictionary, "d.txt");
...
void getDictionaryFromFile(vector<string> &g_dictionary, string fileName){..}

但是當我嘗試像下面這樣用我的二維數組做同樣的事情時,我在“solve_point(boardEx);”行上得到一個錯誤表示 char & 類型的引用不能用 boardEx[5][4] 類型的值初始化

#include <stdio.h>   
#include <string>
using namespace std;

void solve_point(char* &board){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}

char*&類型是對指針的引用。 “2d”數組衰減為指向數組的指針。

對於您的數組boardEx ,它將衰減為char(*)[4]類型,它需要是您的函數接受的類型:

void solve_point(char (*board)[4]) { ... }

或者您可以使用模板來推斷數組維度

template<size_t M, size_t N>
void solve_point(char (&board)[M][N]) { ... }

或使用std::array

std::array<std::array<char, 5>, 4> boardEx;

...

void solve_point(std::array<std::array<char, 5>, 4> const& board) { ... }

或使用std::vector

std::vector<std::vector<char>> boardEx(5, std::vector<char>(4));

...

void solve_point(std::vector<std::vector<char> const& board) { ... }

考慮到問題的編輯,使用std::vector的解決方案是唯一可能的便攜式和標准解決方案。

可以使用以下方法定義對 2D 數組的引用:

char (&ref)[5][4] = boardEx;

您可以更改函數以使用相同的語法。

void solve_point(char (&board)[5][4]){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

對於動態分配的數組,最好使用std::vector

int width = 7;
int height = 9;
char boardEx[width][height];

一些編譯器支持作為擴展,但它不是標准的 C++。 相反,使用:

int width = 7;
int height = 9;
std::vecotr<std::vector<char>> boardEx(width, std::vector(height));

相應地更新solve_point

您可以通過值或引用聲明接受數組的函數。

例如(按值)

void solve_point( char ( *board )[4] ){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}

或(參考)

void solve_point(char ( &board )[5][4] ){ 
    printf("solve_point\n");
    //board[2][2] = 'c';
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}

在這兩種情況下,您都可以使用這樣的表達式訪問數組的元素

board[i][j] = 'c';

請記住,如果您有一個多維數組,例如這樣

T a[N1][N2][N3];

其中T是某種類型說明符,那么您可以按以下方式重寫聲明

T ( a[N1] )[N2][N3];

現在要獲取指向數組元素的指針,只需將( a[N1] )替換為( *pa )

T ( *pa )[N2][N3] = a;

要獲得對數組的引用,請重寫其聲明,例如

T ( a )[N1][N2][N3];

並將( a )替換為( &ra )就像

T ( &ra )[N1][N2][N3] = a;

如果你想寫一個通過引用接受不同大小的二維數組的函數,那么你可以寫

template <typename T, size_t M, size_t N>
void solve_point( T ( &board )[M][N] ){ 
    //...
}

int main(){
    char boardEx[5][4];
    solve_point(boardEx);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM