我想在三维空间中创建一个立方体素节点的26个邻居。输入是节点的x,y,z位置和立方体侧的大小。我试图使用for循环但仍未管理。我是编程新手,请帮助我。
答案 0 :(得分:8)
for (int dz = z - 1; dz <= z + 1; ++dz)
{
for (int dy = y - 1; dy <= y + 1; ++dy)
{
for (int dx = x - 1; dx <= x + 1; ++dx)
{
// all 27
if ((dx != x) || (dy != y) || (dz != z))
{
// just the 26 neighbors
}
}
}
}
答案 1 :(得分:1)
这是一个没有嵌套循环的变体。我尝试使用类似于your question的表示法。
// g++ 26neighbours.cpp -o 26neighbours && 26neighbours
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
namespace {
struct Pos {
double x, y, z;
template<class Char, class Traits>
friend std::basic_ostream<Char, Traits>&
operator<< (std::basic_ostream<Char, Traits>& out, const Pos& p)
{
return out << p.x << " " << p.y << " " << p.z;
}
explicit Pos(double x_ = 0, double y_ = 0, double z_ = 0)
: x(x_), y(y_), z(z_)
{
}
};
template <class OutputPosIterator, class InputPosIterator, class Number>
void translate(OutputPosIterator first, OutputPosIterator last,
InputPosIterator delta, Number factor)
{
for ( ; first != last; ++first, ++delta) {
first->x += delta->x * factor;
first->y += delta->y * factor;
first->z += delta->z * factor;
}
}
}
int main(int argc, char *argv[])
{
const Pos delta[] = {
// ruby -e"(-1..1).each{|i| (-1..1).each{|j| (-1..1).each{|k| printf(\"Pos(%2d,%2d,%2d),\n\", i, j, k) if (i!=0 || j!=0 || k!=0)}}}"
Pos(-1,-1,-1),
Pos(-1,-1, 0),
Pos(-1,-1, 1),
Pos(-1, 0,-1),
Pos(-1, 0, 0),
Pos(-1, 0, 1),
Pos(-1, 1,-1),
Pos(-1, 1, 0),
Pos(-1, 1, 1),
Pos( 0,-1,-1),
Pos( 0,-1, 0),
Pos( 0,-1, 1),
Pos( 0, 0,-1),
Pos( 0, 0, 1),
Pos( 0, 1,-1),
Pos( 0, 1, 0),
Pos( 0, 1, 1),
Pos( 1,-1,-1),
Pos( 1,-1, 0),
Pos( 1,-1, 1),
Pos( 1, 0,-1),
Pos( 1, 0, 0),
Pos( 1, 0, 1),
Pos( 1, 1,-1),
Pos( 1, 1, 0),
Pos( 1, 1, 1),
};
const int N = sizeof(delta) / sizeof(*delta);
// find neighbours of somePos
double cube_size = 0.5;
Pos somePos(0.5, 0.5, 0.5);
std::vector<Pos> neighbours(N, somePos);
translate(neighbours.begin(), neighbours.end(), delta, cube_size);
// print neighbours
std::copy(neighbours.begin(), neighbours.end(),
std::ostream_iterator<Pos>(std::cout, "\n"));
std::cout << std::endl;
return 0;
}
答案 2 :(得分:0)
for(int i = 0; i < 27, i++)
{
if(i == 13) continue;
int dx = i%3 -1;
int dy = (i/3)%3 -1;
int dz = i/9 - 1;
process(x+dx,y+dy,z+dz);
}