2014-07-03 89 views
-2

如何創建一個數組大小爲5的動態結構,以這種方式刪除數組元素[2],但不破壞數組[4]?充滿動態結構的C++數組

Struct Bullet 
{ 
int x, y, width, height, velocity; 
}; 

Struct Shooting 
{ 
Bullet charger[MAX_SHOT]; 
Bullet *shoot; 
}; 

int main() 
{ 
for(int i = 0; i<MAX_SHOT; i++) 
{ 
shoot = new Bullet; 
charger[i] = shoot; 
} 

我想要的是一種方式,例如當一顆子彈擊中某物或消失時我可以銷燬它但不破壞充電器。 謝謝。

+1

是的,說實話,你的問題不清楚,相當粗糙。你所擁有的代碼也沒有多大意義。我提供了不錯的建議,但我正在仔細查看你的代碼,它根本不會編譯。如果你想問這個問題,我強烈建議你重新提出你的問題,花更多的時間思考問題以及你真正想要在更高層次上解決的問題(你似乎並沒有足夠理解代碼來描述它以可實施的方式)。 – M2tM

回答

0
/* 
    Your friends here are vector, remove_if, and erase. 
*/ 

#include<vector> // where vector lives. 
#include<algorithm> // where remove_if lives. 

using std::vector; 
using std::remove_if; 

struct Bullet 
{ 
    int x, y, velocity; 
    // Note: I left out width and height because I did not use them at all. 
}; 

struct Ship 
{ 
    int x, y, velocity; 
}; 

int const max_shots_in_air= 10; 
vector<Bullet> shots_in_air; 

// I'm just using a fixed-place Ship as a place to get the starting x and y for each Bullet. 
Ship ship{10,10,0}; 
int const max_bullet_height= 100; 
int const bullet_velocity= 5; 

void fire_shot() 
{ 
    if(shots_in_air.size() < max_shots_in_air) 
    { 
     Bullet new_bullet{ship.x, ship.y, bullet_velocity}; 
     shots_in_air.push_back(new_bullet); 
    } 
} 

void move_bullets() 
{ 
    //First move all the bullets. 
    for(auto& current_bullet : shots_in_air) 
    { 
     current_bullet.y+= current_bullet.velocity; 
    } 
    //Next check for bullets that need removal 
    shots_in_air.erase(remove_if(shots_in_air.begin() 
      , shots_in_air.end() 
      , [] (Bullet const& b) 
      {return b.y > max_bullet_height;})) 
     ; 
} 


void game_loop() 
{ 
    bool in_game= true; 
    while(in_game) 
    { 
     fire_shot(); 
     move_bullets(); 
     // do whatever else 
    } 
} 


int main() 
{ 
    game_loop(); 
}