gpt4 book ai didi

C++、Lambdas、for_each 和内存损坏

转载 作者:行者123 更新时间:2023-11-30 02:54:08 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com