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

标签 c++ lambda

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/

相关文章:

java - Java 8 中的调用方法

python - 属性错误 : 'module' object has no attribute 'func' Only With C++ Invocation

c++ - 在 Linux 中寻找流量控制功能(即 QOS)库

c# - 这个 lambda 函数是如何工作的?

Java 8 foreach 将子对象添加到新列表

c++ - 使用 Qt 在后台线程中定期执行某些 lambda func 的正确方法是什么?

java - 如何使用 Lambda 和 Streams 在 Java 8 中反转单个字符串?

C++14 shared_timed_mutex VS C++11 互斥量

c++ - 从我的程序连接到 mysql Web 数据库

c++ - 类对齐问题