
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!