c + +:通过引用传递2d数组? [英] c++ : pass 2d-array by reference?

查看:116
本文介绍了c + +:通过引用传递2d数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我又回到了c ++,并且在弄清楚如何将2D数组传递给函数时遇到了麻烦.下面的代码是我当前的尝试,我已经能够使用以下方式通过引用传递矢量字符串:

I'm getting back into c++ and am having trouble figuring out how to pass a 2D-array to a function. The code below is my current attempt, I've been able to pass vector strings by reference by using:

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

但是,当我尝试对2d数组执行相同的操作(如下所示)时,在"solve_point(boardEx);"行上出现错误说的是char&类型的引用不能使用类型为boardEx [5] [4]

But when I try to do the same thing with my 2d-array like so below, I get an error on the line "solve_point(boardEx);" said a reference of type char & cannot be initialized with a value of type 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"数组会衰减为指向数组的指针.

The type char*& is a reference to a pointer. A "2d" array decays to a pointer to an array.

对于数组boardEx,它将衰减为类型char(*)[4],该类型必须是函数接受的类型:

For your array boardEx it will decay to the type char(*)[4] which needs to be the type your function accepts:

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


或者您可以使用模板来推导数组尺寸


Or you can use templates to deduce the array dimensions

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的解决方案是唯一可能的便携式标准解决方案.

Considering the edit of the question, the solution using std::vector is the only portable and standard solution possible.

这篇关于c + +:通过引用传递2d数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆