Click here to Skip to main content
15,880,364 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
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:

C#
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;
        }
});


Thanks for your time everyone,
Robbie.
Posted
Updated 23-Jan-11 7:24am
Comments
Sergey Alexandrovich Kryukov 22-Jan-11 20:37pm    
Why do you call this "lambda"?
RobNO 22-Jan-11 20:40pm    
Refer to link: http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions
Emilio Garavaglia 23-Jan-11 2:51am    
The question from SA not "improper", it is the OP question the is malposed. He can break out the lambda (with a return statement!). What it cannot do is breaking the for_each internal loop, since it is not designed to be broken. Actually what he did is not "a lambda", is a "for_each over a lambda", while he's probably looking a for_each_until or similar
RobNO 23-Jan-11 13:00pm    
My bad, I am just a college student a year in...

 
Share this answer
 
Comments
RobNO 22-Jan-11 20:51pm    
Ill accept the answer to this response. An iterator would work just as well but I do think there needs to eventually be away to break out of the function.

Thanks for your time,
RobNO.
Nish Nishant 22-Jan-11 20:55pm    
I agree, perhaps a future version will have a for_each_if or for_each_until implementation.
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;
}


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

Edit: Such a trivial change that I messed it up!
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900