问题描述
我有一个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,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,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,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,y - 1);
}
if(y < this->height - 1){
north_cell = std::pair<uint16_t,y + 1);
}
}
neighborhood[0] = west_cell;
neighborhood[1] = east_cell;
neighborhood[2] = north_cell;
neighborhood[3] = south_cell;
return neighborhood;
}
我必须多次执行此操作,并且我不想因执行不当而使自己陷入困境。 一种选择比另一种更好,还是我绝对错了,还有另一种方法可以有效地做到这一点?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)