在Vector上迭代时将元素添加到Vector [英] Adding an element to a Vector while iterating over it
问题描述
正如标题所说,我想在某些情况下在遍历向量的同时向std::vector
添加一个元素.使用以下代码,我得到一个错误调试断言失败".可以实现我想做的事吗?
As the title says, I want to add an element to a std::vector
in certain cases while iterating through the vector. With the following code, I'm getting an error "Debug assertion failed". Is it possible to achieve what I want to do?
这是我测试过的代码:
#include <vector>
class MyClass
{
public:
MyClass(char t_name)
{
name = t_name;
}
~MyClass()
{
}
char name;
};
int main()
{
std::vector<MyClass> myVector;
myVector.push_back(MyClass('1'));
myVector.push_back(MyClass('2'));
myVector.push_back(MyClass('3'));
for each (MyClass t_class in myVector)
{
if (t_class.name == '2')
myVector.push_back(MyClass('4'));
}
return 0;
}
好吧,我以为for each
是标准的C ++,但似乎是Visual Studio的功能:
Well, I thought for each
was standard C++, but it seems that it's a Visual Studio feature:
在中
推荐答案
在std::vector
中添加或删除项目的行为会使现有的迭代器无效.因此,您不能使用任何依赖迭代器的循环,例如 for each, in
,基于范围的for
, std::for_each()
等.您将不得不循环使用索引,例如:
The act of adding or removing an item from a std::vector
invalidates existing iterators. So you cannot use any kind of loop that relies on iterators, such as for each, in
, range-based for
, std::for_each()
, etc. You will have to loop using indexes instead, eg:
int main()
{
std::vector<MyClass> myVector;
myVector.push_back('1');
myVector.push_back('2');
myVector.push_back('3');
std::vector<MyClass>::size_type size = myVector.size();
for (std::vector<MyClass>::size_type i = 0; i < size; ++i)
{
if (myVector[i].name == '2')
{
myVector.push_back('4');
++size; // <-- remove this if you want to stop when you reach the new items
}
}
return 0;
}
这篇关于在Vector上迭代时将元素添加到Vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!