我正在用节点创建一个十六进制板。我在这段代码中的所有内容都可以完美运行。我的问题是加星号的项目减慢了这个循环的速度,从 ~1 秒到大约 1 分钟。这不是矢量中的项目数,因为如果我将它们全部删除,除了最后一个,它仍然需要~1分钟。无论哪种方式,都没有运行时错误。
for (x = 0; x < size; ++x)
{
for (y = 0; y < size; ++y)
{
this->nodes[x][y].neighbors = std::vector<node>(6);
if ((x == 0) && (y == 0))
{
this->nodes[x][y].neighbors =
{
nodes[x + 1][y],
this->nodes[x][y + 1]
};
}
else if ((x == 0) && (y == max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x + 1][y],
this->nodes[x][y - 1],
this->nodes[x + 1][y - 1]
};
}
else if ((x == max) && (y == 0))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x][y + 1],
this->nodes[x - 1][y + 1]
};
}
else if ((x == max) && (y == max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x][y - 1]
};
}
else if (y == 0 && (x != 0 && x != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x + 1][y],
this->nodes[x - 1][y + 1],
this->nodes[x][y + 1]
};
}
else if (y == max && (x != 0 && x != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x - 1][y],
this->nodes[x + 1][y],
this->nodes[x - 1][y - 1],
this->nodes[x][y - 1]
};
}
else if (x == 0 && (y != 0 && y != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x][y - 1],
this->nodes[x][y + 1],
this->nodes[x + 1][y],
this->nodes[x + 1][y - 1]
};
}
else if (x == max && (y != 0 && y != max))
{
this->nodes[x][y].neighbors =
{
this->nodes[x][y - 1],
this->nodes[x][y + 1],
this->nodes[x - 1][y - 1],
this->nodes[x - 1][y]
};
}
else
{
this->nodes[x][y].neighbors =
{
this->nodes[x + 1][y],
this->nodes[x - 1][y],
this->nodes[x][y - 1],
this->nodes[x + 1][y - 1],
this->nodes[x][y + 1],
this->nodes[x - 1][y + 1]
};
}
}
}
鉴于这个想法是跟踪您知道已预先创建的邻居,您可能只想保留指向它们的引用或指针; 您不应该像当前那样按值复制node
。
您可以使用 vector<reference_wrapper<node>>
或 vector<node*>
,并像这样进行相应的初始化:
nodes[x][y].neighbors = { ref(nodes[a][b]), ref(nodes[c][d])... };
nodes[x][y].neighbors = { &nodes[a][b], &nodes[c][d], ... };
使用指针,当您访问neighbors[n]
时,显然也需要取消引用指针。
关于为什么这么慢...按价值复制意味着将node
抄入neighbours
就是复制所有那些相邻的node
邻居,以及他们的邻居,令人作呕......随着具有长邻居层次结构的节点数量的增加,速度越来越慢。
缓慢来自两件事:
- 最后一个 else 条款受到的打击最大。
- 最后一个子句复制的节点项比其他子句多
几点建议:
- 使用指针或索引,而不是为邻居
node
对象。减少复制。 - 为邻居使用固定大小的数组会更快。将显着改善局部性和记忆力。您必须为该数组添加邻居计数。