通过引用传递列表时出错(c++)
Error when passing list by reference (C++)
我试图在c++中编写一个子程序,以获取一个单元格在正方形网格上的位置,并返回其邻居列表,因此对于大多数单元格,它将返回4个邻居,但边缘上的单元格只会有3个,在角落里只会有2个。我不是一个非常熟练的c++程序员,所以我在这里查找了一些通过引用传递列表的帮助(c++将列表作为参数传递给函数)。
我得到这个错误:
In function ‘void findNeighbours(int, int, int, int, std::list<int, std::allocator<int> >&)’:
error: invalid conversion from ‘int*’ to ‘int’
下面是我的代码:
void findNeighbours(int x, int y, int xSIZE, int ySIZE, list<int>& neighbours){
int n[2]={x-1,y};
int e[2]={x,y+1};
int s[2]={x+1,y};
int w[2]={x,y-1};
switch(x){
case 0: {neighbours.push_back(s);}
case xSIZE-1: {neighbours.push_back(n);}
default: {neighbours.push_back(n);neighbours.push_back(s);}
}
switch(y){
case 0: {neighbours.push_back(e);}
case ySIZE-1: {neighbours.push_back(w);}
default: {neighbours.push_back(e);neighbours.push_back(w);}
}
}
导致错误的行如下所示:情况0:{neighbors .push_back(s);}
但是我看不出我和上面的例子有什么不同。
就像我说的,我不是最熟练的c++程序员,所以请尽可能用简单的语言解释。我习惯使用Python,所以我不太擅长指针等。
提前感谢你的帮助,
FJC
变量s定义为包含两个元素的数组
int s[2]={x+1,y};
而列表的值类型为int
list<int>& neighbours
您正在尝试push_back数组而不是int类型的对象
case 0: {neighbours.push_back(s);}
我认为在任何情况下这个函数都没有意义至少因为这个奇怪的语句
case xSIZE-1: {neighbours.push_back(n);}
case标号应为常量表达式。
s
为数组(int[]
), neighbours.push_back
取单个int
!在示例中使用neighbours.push_back(s[0])
或neighbours.push_back(s[1])
或任何int
一种简单的做法是每次在一行上添加每个邻居。不能在switch语句中使用像xSIZE
这样的非常量表达式。这使得代码非常长,迫切需要重构成更整洁的东西,但这只是一个开始。我也会返回列表,而不是通过引用传递:
list<int> findNeighbours(int x, int y, int xSIZE, int ySIZE){
list<int> neighbours;
int n[2]={x-1,y};
int e[2]={x,y+1};
int s[2]={x+1,y};
int w[2]={x,y-1};
if(x == 0)
{
neighbours.push_back(s[0]);
neighbours.push_back(s[1]);
}
else if (x == xSIZE-1)
{
neighbours.push_back(n[0]);
neighbours.push_back(n[1]);
}
else
{
neighbours.push_back(s[0]);
neighbours.push_back(s[1]);
neighbours.push_back(n[0]);
neighbours.push_back(n[1]);
}
if(y == 0)
{
neighbours.push_back(e[0]);
neighbours.push_back(e[1]);
}
else if (y == ySIZE-1)
{
neighbours.push_back(w[0]);
neighbours.push_back(w[1]);
}
else
{
neighbours.push_back(e[0]);
neighbours.push_back(e[1]);
neighbours.push_back(w[0]);
neighbours.push_back(w[1]);
}
return neighbours;
}
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 为重写std::exception的库生成swig接口时出错
- 导入/导出变量时出错
- PrintWindow函数在notepad.exe中出错