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 th开发者_如何学Cat 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 match
bool (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);
精彩评论