删除循环中向量的元素 [英] Remove elements of a vector inside the loop
问题描述
我知道有一个类似的问题,但我没有设法找到的方式在我的代码,他们的援助。我只想通过检查循环中该元素的属性来删除/删除向量的元素。我该怎么办?我尝试下面的代码,但我收到错误的模糊消息:
I know that there are similar questions to this one, but I didn’t manage to find the way on my code by their aid. I want merely to delete/remove an element of a vector by checking an attribute of this element inside a loop. How can I do that? I tried the following code but I receive the vague message of error:
'operator ='函数在播放器中不可用。
'operator =' function is unavailable in 'Player’.
for (vector<Player>::iterator it = allPlayers.begin(); it != allPlayers.end(); it++)
{
if(it->getpMoney()<=0)
it = allPlayers.erase(it);
else
++it;
}
我该怎么办?
更新:您认为 vector :: erase with pointer member 属于同一个问题?因此我需要一个赋值运算符?为什么?
Update: Do you think that the question vector::erase with pointer member pertains to the same problem? Do I need hence an assignment operator? Why?
推荐答案
您不应该在 it
> for loop:
You should not increment it
in the for
loop:
for (vector<Player>::iterator it=allPlayers.begin();
it!=allPlayers.end();
/*it++*/) <----------- I commented it.
{
if(it->getpMoney()<=0)
it = allPlayers.erase(it);
else
++it;
}
注意注释的部分; it ++
在那里不需要,因为 it
在for-body本身增加。
Notice the commented part;it++
is not needed there, as it
is getting incremented in the for-body itself.
错误'operator ='function在'Player'中不可用,它来自 erase()
的使用, c $ c> operator = 在向量中移动元素。为了使用 erase()
,类 Player
的对象必须是可分配的,这意味着您需要实现 operator =
为玩家
类。
As for the error "'operator =' function is unavailable in 'Player’", it comes from the usage of erase()
which internally uses operator=
to move elements in the vector. In order to use erase()
, the objects of class Player
must be assignable, which means you need to implement operator=
for Player
class.
这篇关于删除循环中向量的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!