簡體   English   中英

將二維數組傳遞給 c++ 中的 function

[英]pass 2d array to a function in c++

我正在嘗試將二維數組傳遞給 c++ 中的 function。問題是它的維度不是通用常數。 我將維度作為用戶的輸入,然后嘗試傳遞數組。 這是我在做什么:

/*
 * boy.cpp
 *
 *  Created on: 05-Oct-2014
 *      Author: pranjal
 */
#include<iostream>
#include<cstdlib>
using namespace std;


class Queue{
private:
    int array[1000];
    int front=0,rear=0;
public:
    void enqueue(int data){
        if(front!=(rear+1)%1000){
            array[rear++]=data;
        }
    }
    int dequeue(){
        return array[front++];
    }
    bool isEmpty(){
        if(front==rear)
            return true;
        else
            return false;
    }
};

class Graph{
public:
    void input(int matrix[][],int num_h){ //this is where I am passing the matrix
        int distance;
        char ans;

        for(int i=0;i<num_h;i++){
            for(int j=0;j<num_h;j++)
                matrix[i][j]=0;
        }
        for(int i=0;i<num_h;i++){
            for(int j=i+1;j<num_h;j++){
                cout<<"Is there route between houses "<<i<<" and "<<j<<": ";
                cin>>ans;
                if(ans=='y'){
                    cout<<"Enter the distance: ";
                    cin>>distance;
                    matrix[i][j]=matrix[j][i]=distance;
                }
            }
        }
        cout<<"The matrix is: \n";
        for(int i=0;i<num_h;i++){
            cout<<"\n";
            for(int j=0;j<num_h;j++)
                cout<<matrix[i][j]<<"\t";
        }
    }
};

int main(){
    Graph g;
    int num_h;
    cout<<"Enter the number of houses: ";
    cin>>num_h;
    int matrix[num_h][num_h];
    g.input(matrix,num_h); //this is where I get an error saying
                           // Invalid arguments ' Candidates are: void input(int (*)[], 
                           // int) '
    return 0;
}

非常感謝幫助。 謝謝你。

您的代碼中的問題:

問題1

void input(int matrix[][],int num_h){

無效的C ++。 在多維數組中,除第一維之外的所有維都必須是常量。 有效聲明為:

// Define a constant at the start of the file.
const int MATRIX_SIZE 200;


void input(int matrix[][MATRIX_SIZE],int num_h){

問題2

int matrix[num_h][num_h];

無效的C ++。 C ++不支持VLA。

建議的解決方案

使用std::vector<std::vector<int>>捕獲2D數組。

更改

void input(int matrix[][],int num_h){

void input(std::vector<std::vector<int>>& matrix){
// You can get the size by calling matrix.size()
// There is no need to pass num_h as an argument.

將調用代碼更改為:

int main(){
    Graph g;
    int num_h;
    cout<<"Enter the number of houses: ";
    cin>>num_h;

    // Construct a 2D array of size num_h x num_h using std::vector
    std::vector<std::vector<int>> matrix(num_h, std::vector<int>(num_h));

    g.input(matrix);
    return 0;
}

而不是傳遞整個矩陣,而是將指針傳遞給矩陣。 為了有效地做到這一點,您需要將矩陣視為2D,但將其作為向量進行管理,或者使用向量的向量。

考慮到第一種情況,您將:

int matrix[num_h * num_h];

g.input(matrix,num_h)

void input(int *matrix,int num_h)

並使用以下元素訪問元素

matrix[i * num_h + j] = 0;

我有一個類似的問題,我試圖將指定為 double[4][4] 的數組提取到我自己的 C++ 矩陣 class 中,該矩陣處理任意維度,因此在內部將矩陣存儲為 double**。 正如大家前面所說的,這些是不等價的——double ** 可以分片,其中 double[4][4] 占據連續的 memory。

但是如果你意識到 double[4][4] 只是一個 double[16],其中數組以行優先順序寫入(例如讀取每一行,然后移動到第二行等),你可以將 double[][] 作為 double* 作為參數傳遞。 這是我的矩陣 class 的代碼子集,以及我如何將 double[4][4] 二維數組傳遞到該 class。

class CMatrix
{
  public:
    CMatrix(unsigned int nRows, unsigned int nCols);
    Set(unsigned int nRows, unsigned int nCols, double* array, bool columnMajor=false)
  protected:
   double** m_M;
}

CMatrix(unsigned int nRows, unsigned int nCols)
{
    unsigned int i = 0;

    m_M = new double*[nRows];
    for (i = 0;i<nRows;i++)
      m_M[i] = new double[nCols];
}

CMatrix::Set(unsigned int nRows, unsigned int nCols, double* array, bool columnMajor)
{
   unsigned int i = 0;
   unsigned int row = 0;
   unsigned int col = 0;

  if (columnmajor) // e.g. FORTRAN
  {
    // same as below but switch order between rows and columns
  }
  else // row major (e.g. C/C++)
  {
    for (i=0;i<nRows*nCols;i++)
    {
      m_M[row][col] = array[i];
      col++;
      if (col % nCols == 0)
      {
         row++;
         col = 0;
      }
    }
  }
}

int main()
{
   CMatrix M(4,4);
   double oldMat[4][4];

   M.Set(4,4,reinterpret_cast<double*>(oldMat));
}

不漂亮,但通過將 double[][] 重新解釋為 double*,我能夠傳遞該值。 但是,當您這樣做時,您會丟失有關行數和列數的信息,這就是為什么我在我的 Set() function 中顯式顯示 arguments 的原因。有了這些知識,您現在可以將二維數組元素轉換為任何內部你需要的格式。 我為列優先添加了一個標志(如果未指定,則默認為行優先),因為我經常將 FORTRAN 代碼轉換為 C++,並且與 C/C++ 不同,FORTRAN 將二維 arrays 轉換為列優先形式的一維 arrays (即在移動到下一列之前向下讀取一列),而 C/C++ 使用行優先形式進行轉換(在移動到下一行之前讀取一行)。

希望這為使用上述 std::vector<> 方法提供了另一種有用的替代方法。 這種方法對我不起作用,因為我沒有更改初始矩陣結構的靈活性——它是其他人創建的 class 中的一個成員。

暫無
暫無

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

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