std :: vector

时间:2018-05-20 17:02:10

标签: c++ vector reference

对于我的一个函数,cppcheck返回: 参数'neighbors'按值传递。它可以作为(const)引用传递,通常更快并且在C ++中推荐。

我知道在传递引用时分配向量两次没有意义,但我真的不知道如何做到这一点.... 我在这里尝试了很多类似的答案,但我找不到真正符合我问题的答案。

类vectorMatrix

此函数获取所有邻居并将其存储在

std::vector<Cell*> vectorMatrix::getCellNeighbors(int x, int y) {
    std::vector<Cell*> neighbors;
    return neighbors;
}

此函数将每个单元格的邻居传递给单元格(存储它们以便快速访问...每次单击都需要它们)

  void vectorMatrix::initCells()
  {
    for (int x = 0; x < _rows; x++)
    {
      for (int y = 0; y < _columns; y++)
      {
        _cellMatrix[x][y]->setNeighbors(getCellNeighbors(x, y));
      }
    }
  }

Class Cell

HXX

std::vector<Cell*> _neighbors;

CXX

void Cell::setNeighbors(std::vector<Cell*> neighbors)
{
  _neighbors = neighbors;
}  

。)如何正确地将向量作为(const?)引用传递。 。)这段代码有效吗?将引用存储到每个单元格内的所有邻居是否有意义? (地图大小最多可达256x256,每个图块都是一个对象)

完整的代码可以在这里找到: https://github.com/JimmySnails/IsometricEngine

1 个答案:

答案 0 :(得分:1)

我是Cppcheck开发人员。

我相信这段代码:

void Cell::setNeighbors(const std::vector<Cell*> &neighbors)
{
  _neighbors = neighbors;
}

应改为:

OutlineButton