错误:" expected unqualified-id before 'int' "、数组、参数、函数、
Error: " expected unqualified-id before 'int' ", array, argument, function,
我是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);
}
注意:
- 我们不需要将向量的大小作为参数传递
- 矢量通过引用传递以避免复制
上面程序的输出可以在这里看到。
相关文章:
- C++函数模板需要 &for 数组参数
- C++ 数组参数不起作用
- 使用数组参数进行函数专用化
- 为什么我的数组参数的方法无法正常工作?(C )
- SWIG - Java 代理类数组参数
- 在 gcc 中使用数组参数编译外部"c"代码
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 如何根据数组参数项类型重载 IDL 中的函数
- 引用谷歌测试/模拟框架中的数组参数
- C++将数组参数传递给函数
- 字符星形数组参数未正确终止
- 如何将德尔菲的"字符串数组"参数翻译成C++?
- 为什么 gcc 无法推断数组参数的模板化大小?(C++11)
- 使用 const char 数组参数分析 constexpr 显示运行时执行
- C++指针数组参数
- 固定大小的多维数组参数
- 为什么数组参数被视为常量数组
- 如何在pgsql中格式化数组参数
- C++字符数组参数在x86编译中包含奇怪的字符
- 对象数组参数 - 错误:字段“字母”的类型不完整