Sunday, May 13, 2012

Lambdas

Yes, I'm still alive hehe
Today, I have been working with C++11 and I did some awesome things.

In this post, I won't explain much, just because I'm still inexperienced but I will.

How many times did you print a vector? And how many lines was needed? Yes, of course. You could make a function but so many times you are just debuging and you aren't really interested with it because you are solving anothers problems of mayor importance.

Here, there's an example with one line to do it. Moreover, I randomly initialized the vector with the same idea.

#include <algorithm>
#include <iostream>
#include <vector>
#include <time.h>

using namespace std;

int main()
{
    // Create a vector object that contains 10 elements.
    vector<int> a(10);

    // randomly initialize using lambda expressions
    srand((unsigned)time(0)); 
    for_each(a.begin(), a.end(), [](/*by reference*/ int& aux){
        aux = rand()%100; } );

    //now, print it
    for_each(a.begin(), a.end(), [](int aux){ cout << aux << endl; } );

    return 0;
}


If you are not used to use for_each, here is an example without use lambdas:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

void printThing(int i){
     cout << i << endl;
}

int main(){
    // Create a vector object that contains 10 elements.
    vector<int> a(10);

    // randomly initialize using lambda expressions
    srand((unsigned)time(0)); 
    for_each(a.begin(), a.end(), [](int& aux){aux = rand()%100; } );

    for_each(a.begin(), a.end(), printThing );
    return 0;
}


And another example using templates, just getting fun:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

template<class T>
void printThing(T i){ //void printThing(const T& i) would be better/faster
     cout << i << endl;
}

int main(){
    // Create a vector object that contains 10 elements.
    vector<int> a(10);

    // randomly initialize using lambda expressions
    srand((unsigned)time(0)); 
    for_each(a.begin(), a.end(), [](int& aux){aux = rand()%100; } );

    for_each(a.begin(), a.end(), printThing<char> );//yes is char, 
    //just to show that we are casting
    return 0;
}

No comments:

Post a Comment