我有一个 2D 环境,我想在其中获取摩尔附近的一些单元格(东、西、北和东单元格)。有时一个单元格只能有 3 或 2 个邻居(如果我们从边界或网格的一角检查)。
在此之上,我想区分没有边界的情况(环面世界,上升的东西再次出现......)。在这种情况下,每个单元格恰好有 4 个邻居。
因此,我制作了该算法的 2 个版本,一个使用 std::vector 坐标,另一个使用 std::array 可选坐标(我将坐标称为一对短整数)。见下文 :
带有成对向量的版本
std::vector<std::pair<uint16_t, uint16_t>>* Environment::getMooreNeighborhood(uint16_t x, uint16_t y) const{
std::vector<std::pair<uint16_t, uint16_t>>* neighborhood = new std::vector<std::pair<uint16_t, uint16_t>>();
std::pair<uint16_t, uint16_t> west_cell(x - 1, y);
std::pair<uint16_t, uint16_t> east_cell(x + 1, y);
std::pair<uint16_t, uint16_t> north_cell(x, y - 1);
std::pair<uint16_t, uint16_t> south_cell(x, y + 1);
if(this->torus){
if(x == this->width - 1){
east_cell.first = 0;
}
else if(x == 0){
west_cell.first = this->width - 1;
}
if(y == 0){
north_cell.second = this->height - 1;
}
else if(y == this->height - 1){
south_cell.second = 0;
}
neighborhood->push_back(east_cell);
neighborhood->push_back(west_cell);
neighborhood->push_back(south_cell);
neighborhood->push_back(north_cell);
}else{
if(x > 0){
neighborhood->push_back(east_cell);
}
if(x < this->width - 1){
neighborhood->push_back(west_cell);
}
if(y > 0){
neighborhood->push_back(north_cell);
}
if(y < this->height - 1){
neighborhood->push_back(south_cell);
}
}
return neighborhood;
}
带有可选对数组的版本
std::array<std::optional<std::pair<uint16_t,uint16_t>>, 4> Environment::getMooreNeighborhood(uint16_t x, uint16_t y) const {
std::array<std::optional<std::pair<uint16_t,uint16_t>>, 4> neighborhood;
std::optional<std::pair<uint16_t, uint16_t>> west_cell;
std::optional<std::pair<uint16_t, uint16_t>> east_cell;
std::optional<std::pair<uint16_t, uint16_t>> north_cell;
std::optional<std::pair<uint16_t, uint16_t>> south_cell;
if(this->torus){
if(x == this->width - 1){
east_cell = std::pair<uint16_t, uint16_t>(0, y);
}
else if(x == 0){
west_cell = std::pair<uint16_t, uint16_t>(this->width - 1, y);
}
if(y == 0){
north_cell = std::pair<uint16_t, uint16_t>(x, this->height - 1);
}
else if(y == this->height - 1){
south_cell = std::pair<uint16_t, uint16_t>(x, 0);
}
}else{
if(x > 0){
east_cell = std::pair<uint16_t, uint16_t>(x - 1, y);
}
if(x < this->width - 1){
west_cell = std::pair<uint16_t, uint16_t>(x + 1, y);
}
if(y > 0){
north_cell = std::pair<uint16_t, uint16_t>(x, y - 1);
}
if(y < this->height - 1){
north_cell = std::pair<uint16_t, uint16_t>(x, y + 1);
}
}
neighborhood[0] = west_cell;
neighborhood[1] = east_cell;
neighborhood[2] = north_cell;
neighborhood[3] = south_cell;
return neighborhood;
}
我必须多次执行此操作,而且我不想因为执行不当而自取其辱。一个选择比另一个更好还是我绝对错了,还有另一种有效的方法?