2008-11-28 35 views
2

我想在3維空間中創建立方體素節點的26個相鄰節點。輸入是節點的x,y,z位置和立方體的大小。我正在嘗試使用for循環,但尚未管理。我在編程方面很新手,請幫助我。在3d空間中創建相鄰節點的循環

回答

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 
     } 
    } 
    } 
} 
+0

你可能需要做一些邊界邊緣的情況下檢查,但你絕對回答了這個問題。 +1 – 2008-11-28 23:35:03

+0

修正錯字:++ z,y,x應分別爲++ dz,dy,dx。 – strager 2008-11-29 00:29:01

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; 
} 
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); 
}