是否有可能突破lambda?

是否有可能突破lambda?

问题描述:

大家好,

是否有可能突破lambda?我想知道的原因是,当我进入if语句时,我要完成的功能已经完成,因此不需要继续遍历向量.

这是我目前正在处理的代码:

Hey Everyone,

Is it possible to break out of a lambda? The reason why I am wondering is that when I get in to the if statement The functionality of what I am trying to accomplish is complete therefore I do not need to continue iterating through the vector.

Here is the code I am currently working on:

std::for_each(records_.begin(), records_.end(),[&id, &updateRecord](Record & record)
{
        bool isFound = false;
        isFound = record.get_record().find(id) == 2;
        if (isFound)
        {
                record.set_record(updateRecord);
                //I want to break out of the lambda right here.
                return;
        }
});



谢谢大家的宝贵时间,
Robbie.



Thanks for your time everyone,
Robbie.

非常好的S.O.有关同一主题的主题:

http://*.com/questions/760221/breaking-in-stdfor-each-loop [^ ]
Very good S.O. thread on this same topic:

http://*.com/questions/760221/breaking-in-stdfor-each-loop[^]


出现问题的原因是std :: for_each旨在遍历您提供给它的整个范围,而不会中断.如果您确实希望某些东西能够尽早终止,则可以使用std :: find_if进行操作,前提是您将lambda更改为布尔谓词(这是相当琐碎的更改):

The reason you''re having the problem is that std::for_each is meant to traverse the entire range you supply to it and not break. If you really want something to be able to terminate early you can do it with std::find_if provided you change your lambda to be a boolean predicate (which is a fairly trivial change):

[&id, &updateRecord](Record & record)->bool
{
    if( record.get_record().find(id) == 2 )
    {
        record.set_record(updateRecord);
        return true;
    }
    return false;
}



您可能还想重命名find_if,以表明您实际上并不是在尝试查找某些东西,只是迭代到条件为止.

干杯,



如此微不足道的变化使我搞砸了!



You might want to rename find_if as well to show that you''re not actually trying to find something, just iterating until a condition.

Cheers,

Ash

Such a trivial change that I messed it up!