迭代向量,边走边删除某些项目

2021-12-08 00:00:00 data-structures loops iterator vector c++

我有一个 std::vector m_vPaths;我将迭代这个向量并随时调用 ::DeleteFile(strPath) .如果我成功删除了文件,我会将其从向量中删除.我的问题是我可以避免使用两个向量吗?是否有不同的数据结构可能更适合我需要做的事情?

I have a std::vector m_vPaths; I will iterate this vector and call ::DeleteFile(strPath) as I go. If I successfully delete the file, I will remove it from the vector. My question is can I get around having to use two vectors? Is there different data structure that might be better suited for what I need to do?

示例:使用迭代器几乎可以满足我的要求,但问题是一旦使用迭代器擦除,所有迭代器都将无效.

example: using iterators almost does what I want, but problem is once you erase using an iterator, all iterators become invalid.

 std::vector<std::string> iter = m_vPaths.begin();
    for( ; iter != m_vPaths.end(); iter++) {
        std::string strPath = *iter;
        if(::DeleteFile(strPath.c_str())) {
            m_vPaths.erase(iter);   
                //Now my interators are invalid because I used erase,
                //but I want to continue deleteing the files remaining in my vector.    
        }
    }

我可以使用两个向量并且不再有问题,但是有没有更好、更有效的方法来做我想做的事情?

I can use two vectors and I will no longer have a problem, but is there a better, more efficient method of doing what I'm trying to do?

顺便说一句,如果不清楚,m_vPaths 是这样声明的(在我的班级中):

btw, incase it is unclear, m_vPaths is declared like this (in my class):

std::vector<std::string> m_vPaths;

推荐答案

查看 std::remove_if:

#include <algorithm> // for remove_if
#include <functional> // for unary_function

struct delete_file : public std::unary_function<const std::string&, bool> 
{
    bool operator()(const std::string& strPath) const
    {
        return ::DeleteFile(strPath.c_str());
    }
}

m_vPaths.erase(std::remove_if(m_vPaths.begin(), m_vPaths.end(), delete_file()),
                m_vPaths.end());

使用 std::list停止无效迭代器问题,尽管您失去了随机访问.(和缓存性能,一般)

Use a std::list to stop the invalid iterators problem, though you lose random access. (And cache performance, in general)

为了记录,您实现代码的方式是:

For the record, the way you would implement your code would be:

typedef std::vector<std::string> string_vector;
typedef std::vector<std::string>::iterator string_vector_iterator;

string_vector_iterator iter = m_vPaths.begin();
while (iter != m_vPaths.end())
{
    if(::DeleteFile(iter->c_str()))
    {
        // erase returns the new iterator
        iter = m_vPaths.erase(iter);
    }
    else
    {
        ++iter;
    }
}

但是你应该使用 std::remove_if(重新发明轮子不好).

But you should use std::remove_if (reinventing the wheel is bad).

相关文章