Home >Backend Development >C++ >How to Remove Elements from a `std::vector` During Iteration Without Invalidating Iterators?

How to Remove Elements from a `std::vector` During Iteration Without Invalidating Iterators?

DDD
DDDOriginal
2024-10-31 07:15:30675browse

How to Remove Elements from a `std::vector` During Iteration Without Invalidating Iterators?

Efficient Removal of Elements from a std::vector During Iteration

Question:

How can one efficiently remove elements from a std::vector while iterating over it without invalidating existing iterators? Consider the following scenario:

<code class="cpp">std::vector<std::string> m_vPaths;
for (auto iter = m_vPaths.begin(); iter != m_vPaths.end(); iter++) {
    if (::DeleteFile(iter->c_str())) {
        m_vPaths.erase(iter);  // Invalidates remaining iterators
    }
}</code>

Answer:

The erase() method provided by std::vector invalidates iterators. To avoid this issue, one can utilize the return value of erase() which points to the next valid iterator:

<code class="cpp">std::vector<std::string>::iterator iter;
for (iter = m_vPaths.begin(); iter != m_vPaths.end(); ) {
    if (::DeleteFile(iter->c_str()))
        iter = m_vPaths.erase(iter);  // Sets iter to next valid element
    else
        ++iter;
}</code>

The above is the detailed content of How to Remove Elements from a `std::vector` During Iteration Without Invalidating Iterators?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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