从ints向量删除int的问题

Problems erasing an int from a vector of ints

本文关键字:问题 int 删除 ints 向量      更新时间:2023-10-16

我的目标是拥有大型的弹道对象向量,以跟踪当前活跃的每个射击/子弹/导弹。但是,我还需要每个瓷砖才能知道哪个弹道对象正上方(出于渲染目的(,因此我试图使每个瓷砖都有一个ints的小矢量,每个瓷砖都是较大的弹道向量的索引来描述哪个在任何给定的框架上都高于它

我的问题是我正在尝试从INT的向量删除INT,但是我不断获得:

no instance of overloaded function "std::vector<_Ty, _Alloc>::erase [with _Ty=int, _Alloc=std::allocator<int>]" matches the argument list
std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>> std::vector<int,std::allocator<_Ty>>::erase(std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<int>>>,std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<int>>>)': cannot convert argument 1 from 'int' to 'std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<int>>>

我有:

extern std::vector<BallisticObject> BallisticVector;

我有瓷砖:

class Tile
{
public:
    Tile(float height, char type);
    ~Tile();
    unsigned char myType;
    float myHeight;
    //future optimization: change below to forward_list
    std::vector<int> Indices_of_Ballistic_Objects_Above_Me;
}; 

我有一个来自ballisticsObject.cpp的摘要:

void BallisticObject::Explode()
{
int TileOverX = location.x / 64;
int TileOverY = location.y / 64;
if (TileOverX >= 0 && TileOverX < MAP_WIDTH && TileOverY >= 0 && TileOverY < MAP_HEIGHT) //if it's within bounds
    if (location.z <= Map[TileOverX][TileOverY]->myHeight + 1.0f) //if it's close to the ground
    {
        this->active = 0;
        Map[TileOverX][TileOverY]->myHeight -= 1.0f; //chip away at the ground
        //now look through the vector of integers (which are indices into the global ballistics vector) and find myself (one that matches my own index)
        for (int i = 0; i < Map[TileOverX][TileOverY]->Indices_of_Ballistic_Objects_Above_Me.size(); i++)
        {
            if (Map[TileOverX][TileOverY]->Indices_of_Ballistic_Objects_Above_Me[i] == myIndex) //found myself
            {
                //remove myself from the tile's list of ballistics object that are above it
                Map[TileOverX][TileOverY]->Indices_of_Ballistic_Objects_Above_Me.erase(i);
                break;
            }
            std::cout << "Error: ballistics object couldn't find itself in the tile's vector of indices!n";
        }
    }
}

我有一种na的感觉,我要么做一个小事,要么做错了一件大事...

使用erase-remove_idiom:

auto& v = Map[TileOverX][TileOverY]->Indices_of_Ballistic_Objects_Above_Me;
v.erase(std::remove(v.begin(), v.end(), myIndex));

,如果您想检查缺少的值,则可以:

auto& v = Map[TileOverX][TileOverY]->Indices_of_Ballistic_Objects_Above_Me;
auto old_size = v.size();
v.erase(std::remove(v.begin(), v.end(), myIndex));
if (old_size == v.size()) {
     std::cout <<
        "Error: ballistics object couldn't find itself in the tile's vector of indices!n";
}