Removing item from vector while iterating?

后端 未结 8 2111
小鲜肉
小鲜肉 2020-11-27 15:40

I have a vector that holds items that are either active or inactive. I want the size of this vector to stay small for performance issues, so I want items that have been mark

8条回答
  •  难免孤独
    2020-11-27 16:40

    If someone need working on indexes

    vector vector;
    for(int i=0;i<10;++i)vector.push_back(i);
    
    int size = vector.size();
    for (int i = 0; i < size; ++i)
    {
        assert(i > -1 && i < (int)vector.size());
        if(vector[i] % 3 == 0)
        {
            printf("Removing %d, %d\n",vector[i],i);
            vector.erase(vector.begin() + i);
        }
    
        if (size != (int)vector.size())
        {
            --i;
            size = vector.size();
            printf("Go back %d\n",size);
        }
    }
    

提交回复
热议问题