Removing Elements from a std::Vector During Iteration
When you have a vector of elements and need to remove items while iterating through it, the erase() method can cause difficulties. Erasing an element invalidates all iterators pointing to subsequent elements.
Iterators and erase()
Consider the following code:
<code class="cpp">std::vector<std::string> m_vPaths; ... for (auto iter = m_vPaths.begin(); iter != m_vPaths.end(); iter++) { std::string strPath = *iter; if (::DeleteFile(strPath.c_str())) { m_vPaths.erase(iter); // Iterators become invalid after erase } }</code>
After the first successful file deletion, the iterator pointing to the next element becomes invalid. This complicates the continuation of the iteration.
Using Two Vectors
One solution is to use two vectors: one to iterate through and another to store the elements to be deleted. While this works, it introduces additional memory overhead and complexity.
Alternative Data Structures
There are data structures that are more suitable for removing elements during iteration, such as:
These structures maintain a sorted or unordered collection of values, and removal does not invalidate other elements.
Using std::remove_if
Alternatively, you can use the std::remove_if() algorithm to remove specific elements from the vector before deleting them. This ensures that iterators remain valid:
<code class="cpp">auto iter_new_end = std::remove_if(m_vPaths.begin(), m_vPaths.end(), [](const std::string& strPath) { return ::DeleteFile(strPath.c_str()); }); m_vPaths.erase(iter_new_end, m_vPaths.end());</code>
Conclusion
Depending on your specific requirements, you can choose the best approach from:
The above is the detailed content of How to Safely Remove Elements from a std::vector During Iteration?. For more information, please follow other related articles on the PHP Chinese website!