【发布时间】:2020-08-15 17:32:01
【问题描述】:
所以,我有这个代码:
int cols = 5, rows = 5;
class Node
{
public:
Node()
{
this->x = 0;
this->y = 0;
}
Node(int i, int j)
{
this->x = i;
this->y = j;
}
void AddNeighbors(Node** grid)
{
if (this->x < cols - 1)
{
this->neighbors.push_back(grid[this->x + 1][this->y]);
}
if (this->x > 0)
{
this->neighbors.push_back(grid[this->x - 1][this->y]);
}
if (this->y < rows - 1)
{
this->neighbors.push_back(grid[this->x][this->y + 1]);
}
if (this->y > 0)
{
this->neighbors.push_back(grid[this->x][this->y - 1]);
}
}
int x;
int y;
vector<Node> neighbors;
bool operator == (Node n2)
{
return this->x == n2.x && this->y == n2.y;
}
bool operator != (Node n2)
{
return this->x != n2.x && this->y != n2.y;
}
};
void RemoveFromVector(vector<Node> &nodesSet, Node element)
{
vector<Node>::iterator it = nodesSet.begin();
for (int i = nodesSet.size() - 1; i >= 0; i--)
{
if (nodesSet[i] == element)
{
advance(it, i);
nodesSet.erase(it);
break;
}
}
}
bool ExistsInVector(vector<Node>& nodesSet, Node element)
{
for (int i = 0; i < nodesSet.size(); i++)
{
if (nodesSet[i] == element)
{
return true;
}
}
return false;
}
int main()
{
Node** grid;
grid = new Node* [cols];
for (int i = 0; i < cols; i++)
{
grid[i] = new Node[rows];
for (int j = 0; j < rows; j++)
{
Node node = Node(i, j);
grid[i][j] = node;
}
}
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
grid[i][j].AddNeighbors(grid);
}
}
}
当我必须存储邻居时,我遇到了很多问题,因为它们不是引用类型。在程序的某个时刻,我必须访问邻居的邻居,但他们没有邻居:)
所以,我知道我必须将邻居存储为参考,但它会破坏大部分内容(例如,我需要重载两个函数:RemoveFromVector 和 ExistsInVector,因此它们必须获取 Node* 元素作为参数) .也许可以创建 Node 类作为参考,但它不会破坏一切?
UPD:我有这样的问题是因为我在大部分编程时间都使用 Ruby,其中大部分内容都是参考,并且给定的代码肯定可以在 Ruby 中工作。
【问题讨论】:
-
使用指针...最好是智能指针。