Home > Backend Development > C++ > body text

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

DDD
Release: 2024-10-31 07:15:30
Original
496 people have browsed it

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

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

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!

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
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!