1

让我们Action成为一个具有is_finished方法和数字tag属性的类。让我们this->vactions成为一个std::vector<Action>

目的是迭代向量并识别那些完成的动作,将它们的标签存储在 a 中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迭代器,但没有找到有关它的信息。如果真的发生了怎么办?向量可以尝试擦除超出“结束”点吗?

4

1 回答 1

3

std::remove_if不保留要删除的元素的值(请参阅cppreference)。在调用之前获取标签值remove_if- 就像你在第二种情况下所做的那样 - 或者std::partition改为使用。

于 2013-06-27T22:09:09.527 回答