让Action
是一个类 is_finished
方法和一个数字 tag
属性(property)。
让this->vactions
成为std::vector<Action>
目的是迭代 vector 并识别完成的那些Actions,
将他们的标签存储在 std::vector<unsigned int>
中并删除操作。
我尝试使用 lambdas 和一点点,想出了一点点 读起来很好但会导致内存损坏的代码。 “扩展”版本, 另一方面,按预期工作。
我怀疑 remove_if 部分有犯规行为,但我想不通 出了什么问题。
这是示例代码。
这会导致内存损坏
std::vector<unsigned int> tags;
auto is_finished=[p_delta](Action& action) -> bool {return action.is_finished();};
//This is supposed to put the finished actions at the end of the vector and return
//a iterator to the first element that is finished.
std::vector<Action>::iterator nend=remove_if(this->vactions.begin(), this->vactions.end(), is_finished);
auto store_tag=[&tags](Action& action)
{
if(action->has_tag())
{
tags.push_back(action->get_tag());
}
};
//Store the tags...
for_each(nend, this->vactions.end(), store_tag);
//Erase the finished ones, they're supposed to be at the end.
this->vaction.erase(nend, this->vaction.end());
if(tags.size())
{
auto do_something=[this](unsigned int tag){this->do_something_with_tag(tag);};
for_each(tags.begin(), tags.end(), do_something);
}
另一方面,这按预期工作
std::vector<Action>::iterator ini=this->vactions.begin(),
end=this->vactions.end();
std::vector<unsigned int> tags;
while(ini < end)
{
if( (*ini).is_finished())
{
if((*ini).has_tag())
{
tags.push_back((*ini).get_tag());
}
ini=this->vaction.erase(ini);
end=this->vaction.end();
}
else
{
++ini;
}
}
if(tags.size())
{
auto do_something=[this](unsigned int tag){this->do_something_with_tag(tag);};
for_each(tags.begin(), tags.end(), do_something);
}
我敢肯定这里有一些菜鸟错误。你能帮我找出来吗?
我认为 for_each
可能正在更新我的 nend
迭代器但找到
没有关于它的信息。如果它发生了怎么办? vector 能否尝试删除超出“结束”点的内容?
最佳答案
std::remove_if
不保留要删除的元素的值(参见 cppreference )。在调用 remove_if
之前获取标记值 - 就像在第二种情况下所做的那样 - 或者使用 std::partition
相反。
关于C++、Lambdas、for_each 和内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17353551/