2012-04-29 8 views
0

私が試したすべての文法エラーが発生します。誰かがコメントの代わりに何を置くべきか教えてもらえますか?これは私の初めてのベクトル作業です。このような状況でベクターからアイテムを削除するにはどうすればよいですか?

EntityListは、Entityクラスの静的なベクトルです。

for(int i = 0;i < (int)Entity::EntityList.size();i++) { 
    if(!Entity::EntityList[i]) continue; 

    if(Entity::EntityList[i]->isDead){ 
     //Erase from vector 
     //Decrement i? 
    } 

    Entity::EntityList[i]->OnLoop(); 
} 

コメントの代わりに入力する必要がありますか?私はいくつかのことを試みましたが、何も動作しません。たとえば、Entity :: EntityList.erase(i);動作しません。私は理解していない、次のエラーを取得:

は、私はパラメータの使用int型を参照してください「のstd :: _ Vector_const_iterator < _Myvec>」

すべての例に「int型からパラメータ1を変換することはできません、私は何をすべきか分からない。

また、削除後にベクトルの要素がシフトダウンされるため、項目を削除した後にiを減らして同じ値のループを再度実行する必要がありますか?それとももっと優雅なやり方ですか?

+1

'int'引数を使って' std :: vector :: erase'の例を実際に見た場合、それらは間違っています。 *イテレータ*が必要です。 http://www.cplusplus.com/reference/stl/vector/erase/ – jamesdlin

答えて

2

あなたは試みることができる:

Entity::EntityList.erase(Entity::EntityList.begin() + i); 

そして、はい、あなたは私をデクリメントする必要があります。

2

Erase/Remove idiomを使用することをおすすめします。 std::remove_ifの結果をvector::eraseに入力できます。すべて設定する必要があります。

ここ
entityList.erase(
    std::remove_if(entityList.begin(), entityList.end(), isEntityDead)); 

は一例です:あなたはそれを助けることができるかどう

#include <algorithm> 
#include <vector> 

class Entity { 
public: 
    bool isDead; 
}; 

// Need this since isDead isn't a member function of Entity 
bool isEntityDead(Entity& entity) { 
    return entity.isDead; 
} 

int main(int argc, char** argv) { 
    Entity ent1 = Entity(); 
    ent1.isDead = false; 
    Entity ent2 = Entity(); 
    ent2.isDead = true; 
    Entity ent3 = Entity(); 
    ent3.isDead = false; 

    std::vector<Entity> entityList; 
    entityList.push_back(ent1); 
    entityList.push_back(ent2); 
    entityList.push_back(ent3); 

    std::cout << "Before removing anything: " << entityList.size() << std::endl; 

    entityList.erase(std::remove_if(entityList.begin(), entityList.end(), isEntityDead)); 

    std::cout << "After remove/erase: " << entityList.size() << std::endl; 

    return 0; 
} 

私はあなたがそれをループしている間ベクトルの内容を変更しないをお勧めしますそれは次のようになります。死んだエンティティをゲームループの終わりに削除する必要がある場合は、どのエンティティが「死んでいる」かを把握し、「死んだリスト」に入れてから「死んだリスト」内のものを削除する方が良いエンティティリストを一度にすべて削除します。

関連する問題