Home > Article > Backend Development > How to Efficiently Erase Elements from a Vector During Iteration Without Invalidating the Iterator?
When iterating through a vector, it can be necessary to remove elements that meet certain criteria. However, straightforward removal can invalidate the iterator used for looping. This article provides a solution for efficiently erasing elements without using the v[i] method.
Maintaining the Iterator After Erase
The erase() method returns a new iterator pointing to the element after the removed element. This allows for continued iteration by updating the loop condition:
<code class="cpp">for(iterator it = begin; it != end(container); it = vec.erase(it)) { if (it->somecondition()) { it = vec.erase(it); } }</code>
Combining remove_if and erase
To optimize the removal process, consider using std::remove_if and erase together:
<code class="cpp">iterator it = std::remove_if(begin, end, pred); vec.erase(it, vec.end());</code>
This approach separates the removal of eligible elements from their actual removal, resulting in a faster O(N) operation.
Example with Template-Based Removal
To generalize the removal process, use a template-based predicate and remove_by_caller class:
<code class="cpp">class remove_by_caller { public: remove_by_caller(AguiWidgetBase* pWidget) : mWidget(pWidget) {} template <typename T> bool operator()(const T& pX) const { return pX.getCaller() == mWidget; } private: AguiWidgetBase* mWidget; }; std::vector<AguiTimedEvent>::iterator it = std::remove_if(timedEvents.begin(), timedEvents.end(), remove_by_caller(widget)); timedEvents.erase(it, timedEvents.end());</code>
Through these approaches, it is possible to efficiently erase elements from a vector while maintaining the iterator.
The above is the detailed content of How to Efficiently Erase Elements from a Vector During Iteration Without Invalidating the Iterator?. For more information, please follow other related articles on the PHP Chinese website!