C++ remove_if on a vector of objects

前端 未结 2 1361
予麋鹿
予麋鹿 2020-12-01 07:50

I have a vector (order is important) of objects (lets call them myobj class) where I\'m trying to delete multiple objects at a time.

class vectorList
{

             


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 08:14

    A predicate is basically a conditional comparison. It can be a function or object. Here's an example using new C++ lambdas. This code will go through the vector and remove the values equal to 3.

    int arg[6] = {1, 2, 3, 3, 3, 5};
    std::vector vec(arg, arg+6);
    vec.erase(
       std::remove_if(
          vec.begin(), vec.end(),
          [](int i){ return i == 3;}),
       vec.end());
    

    Edit: For pointers let's say you had a vector or interfaces you could set them to nullptr then remove them in a batch with pretty much the same code. In VS2008 you won't have lambdas so make a comparison predicate function or struct instead.

    bool ShouldDelete(IAbstractBase* i)
    {
        return i == nullptr;
        // you can put whatever you want here like:
        // return i->m_bMarkedDelete;
    }
    
    std::vector vec;
    vec.erase(
       std::remove_if(
          vec.begin(), vec.end(),
          ShouldDelete),
       vec.end());
    

提交回复
热议问题