2017-05-22 38 views
1

我有一些代码来生成网格坐标(SDL_Point只包含两个int S代表X和Y)与圆形:中点圆圈没有重复?

std::vector<SDL_Point> circle(const SDL_Point & start, const int radius) 
{ 
    int x{ radius }, y{ 0 }; 
    int xChange{ 1 - 2 * radius }; 
    int yChange{ 1 }; 
    int rError{ 0 }; 

    std::vector<SDL_Point> circle; 
    SDL_Point coord; 

    while (x >= y) 
    { 
     /* Due to circle's symmetry, we need only to calculate 
      points in the first 45º of the circle. 
     */ 

     coord = { start.x + x, start.y + y }; // Octant 1. 
     circle.push_back(coord); 
     coord = { start.x - x, start.y + y }; // Octant 4. 
     circle.push_back(coord); 
     coord = { start.x - x, start.y - y }; // Octant 5. 
     circle.push_back(coord); 
     coord = { start.x + x, start.y - y }; // Octant 8. 
     circle.push_back(coord); 
     coord = { start.x + y, start.y + x }; // Octant 2. 
     circle.push_back(coord); 
     coord = { start.x - y, start.y + x }; // Octant 3. 
     circle.push_back(coord); 
     coord = { start.x - y, start.y - x }; // Octant 6. 
     circle.push_back(coord); 
     coord = { start.x + y, start.y - x }; // Octant 7. 
     circle.push_back(coord); 

     ++y; 
     rError += yChange; 
     yChange += 2; 

     if (2 * rError + xChange > 0) 
     { 
      --x; 
      rError += xChange; 
      xChange += 2; 
     } 
    } 

    return circle; 
} 

这工作不错,但我注意到,从一个复制时的一些坐标添加两次八分到另一个(在画面更清晰灰色):

midpoint circle

是否存在已知的方式,以避免这些重复的或者我应该将它们添加到vector之前只检查?

我想知道最有效的方法是什么。我还没有找到任何答案,我猜这通常不是打印普通彩色圆圈时需要考虑的问题。

编辑:我需要向量作为输出。

谢谢! :)

+0

它是否有任何*实际*性能或正确性影响?如果不是,那么忽略它总是一个有效的选择。 –

回答

2

如果你考虑你的代码在做什么,有两种情况会产生重复:当y是0(沿着你的图的边缘)和x == y(圆圈中的对角线)。您可以在适当的coord计算之前为这些条件添加检查以排除它们。

例如,当y为零时,coord = { start.x + x, start.y + y };coord = { start.x + x, start.y - y };会生成相同的值。

+0

严,你说得对,也许这是最简单的解决方案。谢谢,我会尝试! – JoePerkins

+0

是的,那工作:) – JoePerkins

3

你可以使用一个容器,实施唯一性,就像

std::set<SDL_Point> 

,然后用插入法来代替的push_back的。

+0

我正在考虑这样做,但它真的有效吗?我不确定。无论如何,我需要一个向量作为输出,所以我将不得不复制该集合的内容。 – JoePerkins

+0

是的 - 它很高效。至少和你想做的其他任何事情一样有效,以确保向量中的唯一性。 –

+0

任何特定的原因,你需要一个载体?也许这可以用set来完成。 –