Sign in to follow this  
littlekid

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

Recommended Posts

littlekid    229
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:
for (TaskListType::iterator iter=activeTaskList.begin(); iter!=activeTaskList.end(); ++iter)
{
	(*iter)->forceKill = TRUE;
}

case 2:
for (TaskListType::iterator iter=activeTaskList.begin(); iter!=activeTaskList.end();)
{
	TASK_NODE* taskNode = (*iter);

	++iter;

	if (taskNode->forceKill == FALSE && taskNode->task->CanKill() == FALSE)
	{
		taskNode->task->OnSuspend();

		suspendedTaskList.splice(suspendedTaskList.end(), activeTaskList, taskNode->iter);

		taskNode->iter = (--suspendedTaskList.end());

		taskNode->active = FALSE;
	}
}

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 this post


Link to post
Share on other sites
DevFred    840
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 this post


Link to post
Share on other sites
Zao    985
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.");
}
}


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this