Tuesday, May 31, 2011

C++ Lambdas.

lambda functions enable us to not only write functions in the middle of others, but to more importantly pass expressions as arguments to a function.

The documentation for lambdas on the internet is sparse, so bear with me if there is a mistake here or there.

Some simple examples of their use:



#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;



bool IsEqualWithoutCase( string first, string second ){
auto upper = [] ( string::value_type &ch ) { ch = toupper(ch) }; //<-- lambda
for_each( first.begin(), first.end(), upper );
for_each( second.begin(), second.end(), upper );
return first == second;
}


int main()
{
string input, comp = "Hello World";
getline(cin,input);
cout << (IsEqualWithoutCase(input,comp) ? "That is correct." : "Wrong answer.") << endl;
}

15 comments:

  1. I suck at coding, gave it up after high school.

    ReplyDelete
  2. I'm going to learn C++ next year, this is really interesting!

    ReplyDelete
  3. I always Tried to get into coding... My poor attention span made me never be able to complete simple hello worlds. Oh well! I'm glad you're able to get into it!

    ReplyDelete
  4. Never heard of these functions

    ReplyDelete
  5. Good stuff, might come in handy some day!

    ReplyDelete
  6. I happen to be a comp sci major. lamdas are pretty useful! :D

    ReplyDelete
  7. I suck at coding as well. maybe I will learn a thing or two here.

    ReplyDelete
  8. Lambdas are really cool!

    auto f = [] (const char *msg) { cout << msg << endl; };

    f("Hello World!");

    ReplyDelete
  9. Lol I really need to learn how to do this. After seeing people do it, it just seems awesome

    ReplyDelete
  10. interesting, its like a little port between two functions

    ReplyDelete
  11. Awesome, this is pretty cool, sure i'll try it out next time I start on a project

    ReplyDelete