通过引用传递列表时出错(c++)

Error when passing list by reference (C++)

本文关键字:出错 c++ 列表 引用      更新时间:2023-10-16

我试图在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;
}