Home > Backend Development > C++ > body text

How to Efficiently Erase Elements from a Vector During Iteration Without Invalidating the Iterator?

Susan Sarandon
Release: 2024-11-04 07:37:02
Original
1016 people have browsed it

How to Efficiently Erase Elements from a Vector During Iteration Without Invalidating the Iterator?

Efficient Erasing from a Vector During Iteration

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!