问题描述
我有一个 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.
我可以使用两个向量并且不再有问题,但是有没有更好、更有效的方法来做我想做的事情?
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::remove_if
:
使用 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:
但是你应该使用 std::remove_if
(重新发明轮子不好).
But you should use std::remove_if
(reinventing the wheel is bad).
这篇关于迭代向量,边走边删除某些项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!