2017-05-22 43 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來完成。 –