简体   繁体   中英

Removing elements from C++ std::vector

What is the proper way to remove elements from a C++ vector while iterating through it? I am iterating over an array and want to remove some elements that match a certain condition. I've been told that it's a bad thing to modify it during traversal.

I guess I should also mention that this is an array of pointers that I need to free before removing them.

EDIT:

So here's a snippet of my code.


void RoutingProtocolImpl::removeAllInfinity()
{
  dv.erase(std::remove_if(dv.begin(), dv.end(), hasInfCost), dv.end()); 
}

bool RoutingProtocolImpl::hasInfCost(RoutingProtocolImpl::dv_entry *entry)
{
  if (entry->link_cost == INFINITY_COST)
  {
    free(entry);
    return true;
  }
  else
  {
    return false;
  }
}

I'm getting the following error when compiling:


RoutingProtocolImpl.cc:368: error: argument of type bool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry*)' does not matchbool (RoutingProtocolImpl::)(RoutingProtocolImpl::dv_entry)'

Sorry, I'm kind of a C++ newb.

The vector's erase() method returns a new iterator that can be used to continue iterating:

std::vecor<MyClass> v = ...;
std::vecor<MyClass>::iterator it = v.begin();
while (it != v.end()) {
  if (some_condition(*it)) {
    it->cleanup(); // or something
    it = v.erase(it);
  }
  else {
    ++it;
  }
}
bool IsEven (int i) 
{ 
  return (i%2) == 0; 
}

//...

std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.erase(std::remove_if(v.begin(),v.end(),IsEven), v.end()); 
//v now contains 1 and 3

Same as Brian R. Bondy's answer, but I'd use a functor rather than a function pointer because compilers are better at inlining them:

struct IsEven : public std::unary_function<int, bool>
{
    bool operator()(int i) 
    { 
      return (i%2) == 0; 
    };
}

//...

std::erase(std::remove_if(v.begin(),v.end(),IsEven()), v.end());

EDIT: In response to If my vector is of pointers that need to be freed after they are removed, how would I do this?

struct IsEven : public std::unary_function<int, bool>
{
    bool operator()(int i) 
    { 
      return (i%2) == 0; 
    };
}

struct DeletePointer : public std::unary_function<myPointedType *, void>
{
    void operator()(myPointedType * toDelete)
    {
        delete toDelete;
    };
}

//...

typedef std::vector<something>::iterator Iterator_T;
Iterator_t splitPoint = std::partition(v.begin(),v.end(),IsEven());
std::for_each(v.begin(), splitPoint, DeletePointer());
v.erase(v.begin(), splitPoint);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM