错误:" expected unqualified-id before 'int' "、数组、参数、函数、

Error: " expected unqualified-id before 'int' ", array, argument, function,

本文关键字:数组 参数 函数 int 错误 expected unqualified-id before      更新时间:2024-09-22

我是C++的新手,目前正在通过证书学习这种语言。我以前只使用Python之类的语言。

我发现类似的帖子有相同的内容,但没有一个能与我的代码相关。

我有以下代码来创建一个十六进制游戏。我试着用一个简单的功能来显示每次玩家发出moove时的棋盘。

一开始,我尽量让代码尽可能简单(限制指针和库的使用(。

我有以下错误:hex_game.cpp:9:47:错误:"int"之前应为不合格的id9|void display_current_array(array[size][size],int size({|

下面是我的代码,希望有人能帮忙:


#include <iostream>
#include <stdlib.h>
using namespace std;
#include <vector>
#include <array>

// a void function to display the array after every moove
void display_current_array(array[size][size], int size){

//s=arr.size();
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cout<<array[i][j]<<endl;
}

}

}
int main(){
// the HEX game is a game of size cases represented by an array either filled with a color;
// int size =11; //as asked but we can play on a differnt board
int size;
// ask the player to give a board size
cout << "What is the size of your Hex Board ? ";
cin>> size;
// create the array to represent the board
int array[size][size];


// the player will choose colors that we will store as an enum type
enum colors {BLUE, RED};


// initialize the array: all positions are 0
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
array[i][j]=0;
}

}
display_current_array(array, size);
}

标准C++中,数组的大小必须是编译时常数。所以当你写:

int size;
cin>> size;
int array[size][size]; //NOT STANDARD C++

语句array[size][size];不是标准的c++。

当您写下:时的第二个

void display_current_array(array[size][size], int size){
//...
}

请注意,在函数display_current_array的第一个参数中,没有指定数组包含的元素的类型。因此,这将导致您所得到的错误。

解决方案

避免这些复杂情况的更好方法是使用动态大小的容器,如std::vector,如下所示:

#include <iostream>
#include <vector>
// a void function to display the vector after every moove
void display_current_array(const std::vector<std::vector<int>> &vec){//note the vector is passed by reference to avoid copying

for(auto &row: vec)
{
for(auto &col: row)
{
std::cout << col ;
}
std::cout<<std::endl;
}
}
int main(){
int size;
// ask the player to give a board size
std::cout << "What is the size of your Hex Board ? ";
std::cin>> size;
// create the 2D STD::VECTOR with size rows and size columns to represent the board
std::vector<std::vector<int>> vec(size, std::vector<int>(size));
// the player will choose colors that we will store as an enum type
enum colors {BLUE, RED};
//NO NEED TO INITIALIZE EACH INDIVIDUAL CELL IN THE 2D VECTOR SINCE THEY ARE ALREADY INITIALIED TO 0
display_current_array(vec);
}

注意:

  1. 我们不需要将向量的大小作为参数传递
  2. 矢量通过引用传递以避免复制

上面程序的输出可以在这里看到。