本文介绍了将2d数组传递给c ++中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图传递一个2d数组到c ++中的函数。问题是它的维数不是通用常数。我将维度作为用户的输入,然后尝试传递数组。这是我的目的:
I am trying to pass a 2d array to a function in c++. The problem is that its dimension is not universal constant. I take the dimension as an input from the user and then try to pass the array. Here is what i am doind:
/*
* 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
Problem 1
void input(int matrix[][],int num_h){
无效C ++。在多维数组中,除第一个维度之外的所有值都必须是常量。一个有效的声明是:
is not valid C++. In a multi-dimensional array, all but the first dimension must be constants. A valid declaration would be:
// Define a constant at the start of the file.
const int MATRIX_SIZE 200;
void input(int matrix[][MATRIX_SIZE],int num_h){
b $ b
问题2
int matrix[num_h][num_h];
无效C ++。 VLA在C ++中不受支持。
is not valid C++. VLA are not supported in C++.
建议的解决方案
使用 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数组传递给c ++中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!