迭代矢量,删除某些项目,因为我去 [英] iterate vector, remove certain items as I go
问题描述
我有一个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?
btw,但是不清楚,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)
对于记录,你实现代码的方式是: p>
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;
}
}
$ b < //en.cppreference.com/w/cpp/algorithm/remove> std :: remove_if
(重新发明轮子不好)。
But you should use std::remove_if
(reinventing the wheel is bad).
这篇关于迭代矢量,删除某些项目,因为我去的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!