C++ Passing Dynamic Array Determined by Parameter

寵の児 提交于 2019-12-13 04:44:11

问题


This function has been asked a few times on here but I am interested in a particular case. Is it possible to have the size of the array passed defined by an additional argument?

As an example, let's say I want a function to print a 2D array. However, I the array may not have the same dimensions every time. It would be ideal if I could have additional arguments define the size of that array. I am aware that I could easily switch out the n for a number here as needed but if I have more complex functions with separate header files it seems silly to go and edit the header files every time a different size array comes along. The following results in error: use of parameter 'n' outside function body... which I understand but would like to find some workaround. I also tried with g++ -std=c++11 but still the same error.

#include <iostream>
using namespace std;

void printArray(int n, int A[][n], int m) {
    for(int i=0; i < m; i++){
        for(int j=0; j<n; j++) {
            cout << A[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {

    int A[][3] = {
        {1,2,3},
        {4,5,6},
        {7,8,9},
        {10,11,12}
    };

    printArray(3, A, 4);

    return 0;
}

Supposedly, this can be done with C99 and also mentioned in this question but I cannot figure out how with C++.


回答1:


This works:

template<size_t N, size_t M>
void printArray( int(&arr)[M][N] ) {
  for(int i=0; i < M; i++){
    for(int j=0; j < N; j++) {
      std::cout << A[i][j] << " ";
    }
    std::cout << std::endl;
  }
}

if you are willing to put the code in a header file. As a bonus, it deduces N and M for you.



来源:https://stackoverflow.com/questions/26723463/c-passing-dynamic-array-determined-by-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!