Public Group

# [C++] when to use lambda vs for loops

This topic is 3046 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I have been trying out the new lambda and features in the vs2010. I do know how the lambda can be used to solve functors agony that existed in the past. However when should lambda should or should not be used? For e.g currently i have some code such as
case 1:
{
(*iter)->forceKill = TRUE;
}

case 2:
{

++iter;

{

}
}


case 1 seems to be a trivial problem which i think should be change to use for_each and lambdas. But for case 2 where it involves more code should go ahead and try to convert it to a for_each/lambda scheme? Generally is it more efficient to use lambda functions? (e.g in a extreme case where the lambda body contains a lot of code) do the compiler actually treat them as individual function which get invoke every time?? or are the lambda functions/code flatten out like in a normal for loop (e.g no jmpptr) Thanks

##### Share on other sites
Does VS2010 support the new for loop syntax? Try to replace the first case with this. Does it work?
for (auto task : activeTaskList){    task->forceKill = TRUE;}

##### Share on other sites
Nope it doesn't. I typed it as you have suggest, but its not recognizing the new loop format.

##### Share on other sites
It does however support the following extension, but as that's not 0x, I tend to prefer to stick with BOOST_FOREACH.
for each (auto task in activeTaskList){    task->forceKill = TRUE;}

As for lambdas, I tend to use them where I would use macros otherwise, or as function<> for callbacks and such.
io.post([this, request, response](){	response->waveform = process_file(request->location, request->user_requested);	request->completion_handler(response);});
and
auto create_data_texture = [this](D3DFORMAT fmt){	return dev->CreateTexture(2048, 1, mip_count, 0, fmt, D3DPOOL_MANAGED, &tex, 0);};hr = create_data_texture(D3DFMT_A16B16G16R16F);if (!SUCCEEDED(hr)){	floating_point_texture = false;	hr = create_data_texture(D3DFMT_A2R10G10B10);	if (!SUCCEEDED(hr))	{		hr = create_data_texture(D3DFMT_A8R8G8B8);		if (!SUCCEEDED(hr))			throw std::exception("Direct3D9: could not create texture.");	}}

• 38
• 12
• 10
• 10
• 9
• ### Forum Statistics

• Total Topics
631362
• Total Posts
2999577
×