Pages

boost::function - std::function

The boost::function and the std::function, introduced by the C++0x technical report 1, are used to generalize, and make more usable, the concept of pointer to function. Besides, the function class so defined add more functionality to the pointer to function construct, giving the chance of adding a state to the function, if this is required.

In this first example, we see how to create a function object referring to a function, and how to use it:

#include <iostream>
#include <functional> // std::function
#include "boost/function.hpp" // boost::function

using std::cout;
using std::endl;
using std::function;

namespace
{
bool check(int i, double d)
{
return i > d;
}
}

void function01()
{
boost::function<bool (int, double)> fb = ✓

function<bool (int, double)> fs = ✓

if(fb(10, 1.1))
cout << "Boost function works as expected" << endl;

if(fs(10, 1.1))
cout << "std function works as expected" << endl;
}

In boost and in C++0x the class function looks just the same. In the template parameters we put the return type and, in round brackets, the parameter types.

The code is based on an example provided by "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. An interesting reading indeed.

Go to the full post

rand

Probably the simplest way of generating a pseudo-random sequence is using the couple of functions srand() and rand(), part of the C standard library.

Their usage is quite strightforward. We use srand() to select a specific sequence, and then we call rand() any time we want the next value in our pseudo-random sequence.

We immediately see that the weakest link in this way of proceeding is the startup. If we always feed srand() with the same seed, we always ends up with the same sequence, and that is not usually the expected behaviour.

But for this problem there is a easy solution: we use as a seed the current time. Usually this is enough to guarantee a certain variety in the results.

There is another caveat, though. If you are using VC++, the first number generated by rand() tends to change only slightly as answer to the usage of increasing seed for srand() . Looks like this is a sort of bug, but I didn't investigate much on the matter, since there is a really immediate workaround: discard the first generated value, and start using the second. Well, it is not expecially elegant, but it is cheap and it works fine.

As we can see in the output of the example (when we run it, otherwise trust me), the generated numbers tend to be equally distributed, and that is often what we are expecting by a pseudo-random sequence.

#include <cstdlib>
#include <iostream>
#include <ctime>
#include <vector>
#include <algorithm>

using namespace std;

namespace
{
void dump(vector<int>& v)
{
auto f = [] (int x) { static int i = 0; cout << '[' << ++i << " = " << x << "] "; };
for_each(v.begin(), v.end(), f);
cout << endl;
}
}

int main()
{
vector<int> vec(64, 0);

srand(static_cast<unsigned int>(time(0))); // 1.
rand(); // discard the first value generated

for(int i = 0; i < 6400000; ++i)
{
int value = static_cast<int>((static_cast<double>(rand())/(RAND_MAX + 1)) * 64); // 2.
++vec[value];
}

dump(vec);
system("pause");
}

1. time() returns a time_t value, srand() wants an unsigned int as parameter, with an explicit cast we get rid of a warning about a possible precision loss.
2. As you can see, I was interested in getting pseudo-random numbers in the interval [0..63], so I casted the integer generated by rand() in a double in the interval [0..1), multiplied the result by 64 and casted back to an integer. A lot of casting, but (mostly) harmless.

Go to the full post

Fibonacci multithreading

Let's use the Boost Thread library to develop a simple Fibonacci calculator.

I reckon you already know enough about the Fibonacci function, that is described recursively in this way:
Fibonacci(n) = Fibonacci(n-2) + Fibonacci(n-1)
Where Fibonacci(0) and Fibonacci(1) are defined to be 0 and 1.

If this looks new to you, you can read more about it on wikipedia.

A way of calculating a Fibonacci number would be just sit and wait for the user to tell us which Fibonacci number he actually wants, and only then starting to calculate it. But that would be a loss of time. While the user is pondering on his choice, we could already start doing the job, and putting the results in a cache. As the user tells us which actual number he wants we check if we are lucky, and the result is already available.

That means, we should have a couple of threads, one waiting for the user choice, one working on the Fibonacci calculation.

Then, it is quite natural to think about another optimization. The function that performs the Fibonacci calculation could take advantage of the cache, too. This is not very interesting from the point of view of the multithreading design of this piece of code, but it has its (big) impact on the execution time. You could have fun checking the change in the application performance using it.

Here is the first part of the code, the include file for the class Fibonacci declaration:
#pragma once // 1

#include <vector>
#include <boost/thread.hpp>
#include <boost/thread/condition.hpp>

class Fibonacci
{
private:
    std::vector<unsigned int> values_; // 2
    bool optim_; // 3

    boost::mutex mx_; // 4
    boost::condition cond_; // 5
    boost::thread tCalc_; // 6

    void precalc(); // 7
    unsigned int getValue(unsigned int index); // 8
public:
    static const int MAX_INDEX = 40; // 9

    Fibonacci(bool optim = false);
    ~Fibonacci();

    unsigned int get(unsigned int index); // 10
};
1. This code is for MSVC++2010, it supports this useful pragma directive ("once") to avoid multiple inclusion of the same file.
2. This vector is used to cache the intermediate values.
3. Flag for the performance optimization, by default it is not used.
4. Mutex to rule the access to the cache.
5. Condition used to notify to the reader thread waiting on the vector that the writer thread has generated a new value.
6. The thread that takes care of calculating the Fibonacci numbers.
7. The thread (6) executes this function, to precalculate the Fibonacci numbers.
8. Internal function to get a specific Fibonacci number.
9. This is a toy Fibonacci calculator. The biggest Fibonacci number we could get with it is 40.
10. The user of the Fibonacci class could just ask for a Fibonacci number, through this method.

It's quite easy to use the Fibonacci class. What one should do is just create an object and call its method get() passing the Fibonacci number required:
#include <iostream>
#include "Fibonacci.h"

void fib()
{
    Fibonacci fib;

    int input;
    while(true)
    {
        std::cout << "Your input [0 .. "
            << Fibonacci::MAX_INDEX << "]: ";
        std::cin >> input;
        if(input < 0 || input > Fibonacci::MAX_INDEX)
            break;
        std::cout << "Fibonacci of " << input << " is "
            << fib.get(input) << std::endl;
    }
    std::cout << "Bye" << std::endl;
}
Let's have a look now at the Fibonacci class implementation.

Here is the constructor:
Fibonacci::Fibonacci(bool optim) : optim_(optim)
{
    values_.reserve(MAX_INDEX);
    tCalc_ = boost::thread(&Fibonacci::precalc, this);
}
We already know the max size for our vector, so we reserve immediately enough room for it. Then we start a thread on Fibonacci::precalc() - since it is a non static function we should pass to the boost::thread constructor a pointer to the object we are using, that is "this".

The destructor has just to keep waiting for the tCalc thread to terminate, so it just call join() on it. But, since calculating Fibonacci numbers could be a long and boring affair, it is better to call an interrupt() on that thread, to see if we can cut it shorter. In any case we are destroying the object, so no more calculation is required:
Fibonacci::~Fibonacci()
{
    tCalc_.interrupt();
    tCalc_.join();
}
To get a Fibonacci number we call the get() method. What it does, it is trying to read from the vector the Fibonacci number at the index passed by the caller. Notice that in order to access exclusively the vector it use a lock on the mutex we create just for that reason.

If the element is not already available, we just wait on the condition that the other thread does its job. Any time a new Fibonacci number is generated, we'll get a notification, so another check will be done on the vector size, and the user will get another waiting message - if the expected number is not already calculated - or the return value:
unsigned int Fibonacci::get(unsigned int index)
{
    if(index < 0 || index > MAX_INDEX)
        return 0;

    boost::lock_guard<boost::mutex> lock(mx_);
    while(index >= values_.size())
    {
        std::cout << "Please wait ..." << std::endl;
        cond_.wait(mx_);
    }
    return values_.at(index);
}
Here is precalc(), the function that is run by the other thread. It is just a loop that calls getValue(), the core functionality of this class, the real place where the Fibonacci numbers are computed, then it gains exclusive access to the mutex protecting the vector, puts the newly calculated value in it, and finally notify to the other thread that something has changed:
void Fibonacci::precalc()
{
    for(int iteration = 0; iteration <= MAX_INDEX; ++iteration)
    {
        unsigned int value = getValue(iteration);
        boost::lock_guard<boost::mutex> lock(mx_);
        values_.push_back(value);
        cond_.notify_one();
    }
}
And finally, the actual Fibonacci number calculation. To shorten the working time, we can use the cache - in any case it is already there - otherwise we figure out the value recursively calling getValue().
Notice that we put an interruption_point before the internal calls, in this way we can cancel the execution there, when required:
unsigned int Fibonacci::getValue(unsigned int index)
{
    if(optim_)
    {
        boost::lock_guard<boost::mutex> lock(mx_);
        if(index < values_.size())
            return values_.at(index);
    }

    switch(index)
    {
    case 0:
        return 0;
    case 1:
        return 1;
    default:
        boost::this_thread::interruption_point();
        return getValue(index - 2) + getValue(index - 1);
    }
}

Go to the full post

boost::thread_specific_ptr

The boost::thread_specific_ptr is a smart pointer that knows about multithreading and ensures that each of its instances is specifically allocated for the current thread.

To appreciate the difference with a normal smart pointer we can have a look at this example:

#include <iostream>
#include "boost/thread/thread.hpp"
#include "boost/thread/mutex.hpp"
#include "boost/thread/tss.hpp"
#include "boost/scoped_ptr.hpp"

using namespace std;

namespace
{
   class Count
   {
   private:
      int step_;
      static boost::mutex mio_;
      static boost::thread_specific_ptr<int> ptrSpec_;
      static boost::scoped_ptr<int> ptrUnique_;

   public:
      Count(int step) : step_(step) {}

      void operator()()
      {
         if(ptrSpec_.get() == nullptr) // 2.
         {
            ptrSpec_.reset(new int(0)); // 3.
         }

         for(int i = 0; i < 10; ++i)
         {
            boost::mutex::scoped_lock lock(mio_);
            *ptrSpec_ += step_;
            *ptrUnique_ += step_;
            cout << boost::this_thread::get_id() << ": " << *ptrSpec_ << ' ' << *ptrUnique_ << endl;
         }
      }
   };

   boost::mutex Count::mio_;
   boost::thread_specific_ptr<int> Count::ptrSpec_;
   boost::scoped_ptr<int> Count::ptrUnique_(new int(0)); // 1.
}

void dd05()
{
   boost::thread t1(Count(1));
   boost::thread t2(Count(-1));
   t1.join();
   t2.join();
}
Notice the differences between the scoped_ptr and the thread_specific_ptr.

The scoped ptr is initialized when the variable is defined (1.) and, being a "normal" static data member, is available just in one instance for all the objects of the class Count.

On the other side we have the thread specific ptr. Even though is a static object we have a specific copy of it for each Count object. Given that, we can't expect to have it initialized as any other "normal" static data. We have instead to go through a special routine. Before its first usage we should check (2.) if the pointer is not set, if that is the case, we reset() the value of the smart pointer.

Go to the full post

boost::condition

A typical situation in multithreading context is the writing/reading access on a buffer from different threads. The reading could be done only if buffer is not empty and the writing could be done only if the buffer is not full. That means the the read and write threads should have a way to communicate between them.

That is precisely the what a boost::condition could be used for.

Basically, we should do something like that: the writer should check the buffer, if it is full it should wait for the reader thread to free some space for the new data; besides, the writer should notify the reader when it puts a data in the buffer. On the other side, the reader checks the buffer, if it is empty, waits for the writer to make available new data; when it reads an element of the buffer it pops it, and then notify the other thread that more room is available.

Let's see this example:

#include <iostream>
#include "boost/thread/thread.hpp"
#include "boost/thread/mutex.hpp"
#include "boost/thread/condition.hpp"
#include "boost/circular_buffer.hpp"

using namespace std;

namespace
{
class Buffer : private boost::noncopyable
{
private:
enum { BUF_SIZE = 3 };
boost::condition cond_;
boost::mutex mcb_; // mutex on the buffer
boost::mutex mio_; // mutex for console access

boost::circular_buffer<int> cb_;

public:
Buffer(int size = BUF_SIZE) : cb_(size) {}

void put(int i)
{
{
boost::mutex::scoped_lock lock(mio_);
cout << "sending: " << i << endl;
}

// acquire exclusive access on the buffer
boost::mutex::scoped_lock lock(mcb_);
if(cb_.full())
{
{
boost::mutex::scoped_lock lock(mio_);
cout << "Buffer is full. Waiting..." << endl;
}

// the buffer is full: wait on the lock for a notification
while (cb_.full())
cond_.wait(lock);
}
cb_.push_back(i);
// notify to the other thread that a new item is available
cond_.notify_one();
}

int get()
{
// acquire exclusive access on the buffer
boost::mutex::scoped_lock lock(mcb_);
if(cb_.empty())
{
{
boost::mutex::scoped_lock lock(mio_);
cout << "Buffer is empty. Waiting..." << endl;
}

// the buffer is empty: wait on the lock for a notification
while (cb_.empty())
cond_.wait(lock);
}

int i = cb_.front();
cb_.pop_front();
// notify to the other thread that the buffer is not full anymore
cond_.notify_one();

{
boost::mutex::scoped_lock lock(mio_);
cout << i << " received" << endl;
}

return i;
}
};

const int ITERS = 20;

void writer(Buffer& buf)
{
for (int n = 0; n < ITERS; ++n)
buf.put(n);
}

void reader(Buffer& buf)
{
for (int x = 0; x < ITERS; ++x)
buf.get();
}
}

void dd04()
{
Buffer buf;

// notice the use of boost::ref
boost::thread t1(&reader, boost::ref(buf));
boost::this_thread::sleep(boost::posix_time::milliseconds(5));
boost::thread t2(&writer, boost::ref(buf));

t1.join();
t2.join();
}

The main thread generates two working threads, one on the reader free function and one on the writing free function. Both of them work on the buffer, that is allocated in the main thread and it is passed by reference to the read/write threads. It is necessary to use boost::ref(), otherwise instead of a reference to the Buffer object a copy of it is passed to the free functions.

But the point of this example is in the mechanism of condition wait on a lock, to leave time to the other threads to do something that it is required to the actual thread to go on with its job, and the notify on a condition, to let know to the other threads that something has changed in that context.

Go to the full post

boost::circular_buffer

A circular buffer is quite a useful concept. It is not difficult to adapt a "normal" container to emulate it. Basically, when we are going forward and we reach its end we should just move back to the beginning.

But, as usual, it is not worthy to reinvent the wheel, if someone else it is providing it to us, it works, and it does what we are expecting from it.

This is the case of the circular buffer concept and its boost implementation boost::circular_buffer.

Here is a short example to show how it works:

#include <iostream>
#include "boost/circular_buffer.hpp"

using namespace std;

namespace
{
template <class T>
void dump(boost::circular_buffer<T>& buf)
{
copy(buf.begin(), buf.end(), ostream_iterator<T>(cout, " "));
cout << endl;
}
}

void cirbuf() {
const int BUF_SIZE = 3;
// Create a circular buffer with a capacity for 3 integers.
boost::circular_buffer<int> cb(BUF_SIZE);

// Insert some elements into the buffer.
for(int i = 0; i < BUF_SIZE; ++i)
{
cb.push_back(i);

cout << i << ' ';
if(cb.full())
cout << "buffer full" << endl;
else
cout << "there is still room in the buffer" << endl;
}

dump(cb);

for(int i = 0; i < BUF_SIZE; ++i)
{
cout << cb.front() << ' ';
cb.pop_front();
if(cb.empty())
cout << "buffer empty" << endl;
else
cout << "there is still stuff in the buffer" << endl;
}
}

Go to the full post

boost::thread on a functor

It is possible to create a boost::thread passing to its constructor a functor, in this way we could keep a state for our new thread as private data member of the class representing the functor.

Let's write an application where a couple of threads are create and loop using a private data member. It is worthy noting that since we are accessing a shared resource - the console, where we are printing some logging from our threads - we must use a mutex, to rule the access to it.

#include <iostream>
#include "boost/thread/thread.hpp"
#include "boost/thread/mutex.hpp"

using std::cout;
using std::endl;

namespace
{
class Count
{
static boost::mutex mio_; // 1.
int multi_;
public:
Count(int multi) : multi_(multi) { }

void operator()()
{
for (int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock lock(mio_); // 2.
cout << "Thread " << boost::this_thread::get_id() << " is looping: " << i*multi_ << endl;
}
}
};

boost::mutex Count::mio_; // 3.
}

void dd02()
{
cout << "Main thread " << boost::this_thread::get_id() << endl;
boost::thread t1(Count(1));
boost::thread t2(Count(-1));
t1.join();
t2.join();
cout << "Back to the main thread " << endl;
}

1. this mutex is an implementation detail of Count, it is unique in the class, permitting different threads to access the resource. That's way it is static private.
2. the mutex protect the access to the console, we use a scoped_lock, that means the lock is automatically released when the code reach the end of scope. In this way all threads have a fair chance to get access to the resource.
3. since the mutex is a static member of Count, we should remember to define it.

Actually, in such a simple case it is not worthy to create a class, a free function would be enough, expecially when we realize that we can pass to the thread constructor the parameters for the function - a clever trick from the designer of the thread class.

So, let's rewrite the example using just a free function:

#include <iostream>
#include "boost/thread/thread.hpp"
#include "boost/thread/mutex.hpp"

using namespace std;

namespace
{
boost::mutex mio;

void count(int multi)
{
for(int i = 0; i < 10; ++i)
{
boost::mutex::scoped_lock lock(mio);
cout << boost::this_thread::get_id() << ": " << multi * i << endl;
}
}
}

void dd03()
{
boost::thread t1(&count, 1);
boost::thread t2(&count, -1);

t1.join();
t2.join();
}

Go to the full post

boost::thread

It's quite easy to create a new thread in an application using the boost::thread library.

In its simpler form, we just pass a pointer to a free function to the constructor of a boost::thread object, and that's it. We just have to remember to call a join on the thread object to let the main thread pending on the newly created one.

Here is an example that shows how the thing works:

#include <boost/thread/thread.hpp>
#include <iostream>

using namespace std;

namespace
{
void hello()
{
cout << "This is the thread " << boost::this_thread::get_id() << endl;
}
}

void dd01()
{
cout << "We are currently in the thread " << boost::this_thread::get_id() << endl;
boost::thread t(&hello);
t.join();
cout << "Back to the thread " << boost::this_thread::get_id() << endl;
}

Not much more to say about this example. The boost::thread object is started in the function hello(), that just print its thread id - calling the function get_id(). The main thread waits for the other thread to complete - thanks to the call to join() - then terminates.

Go to the full post

std::transform

If we want to apply the same change to all the elements in a sequence, it is nice to use the std::transform algorithm. As usual, we pass to it a predicate that is delegate to perform the actual change.

If the transformation is not banal we usually write a functor to store the rule that has to be applied. At least, that's what we did when there was no boost or C++0x available.

In the example we see how to implement the transformation "increase the value by ten, than reduce the result by 5%" using boost::bind, and then with the C++0x lambda.

#include <iostream>
#include <list>
#include <functional>
#include <algorithm>
#include <iterator>

#include "boost/bind.hpp"

using namespace std;

namespace
{
template<class T>
void dump(list<T>& lst)
{
copy(lst.begin(), lst.end(), ostream_iterator(cout, " "));
cout << endl;
}

void init(list<double>& lst)
{
lst.clear();
lst.push_back(10.0);
lst.push_back(100.0);
lst.push_back(1000.0);
dump(lst);
}
}


void bind05()
{
list<double> values;

init(values);
auto fb = boost::bind(multiplies<double>(), 0.95, boost::bind(plus<double>(), _1, 10));
transform(values.begin(), values.end(), values.begin(), fb);
dump(values);

init(values);
auto fl = [](double d) { return (d + 10) * 0.95; };
transform(values.begin(), values.end(), values.begin(), fl);

dump(values);
}

Why using boost::bind when with C++0x lambda the code is so straigthforward? Well, maybe when you have to use a compiler that does not support C++0x yet.

The code is based on an example provided by "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. An interesting reading indeed.

Go to the full post

std::count_if and std::find_if

Another place where it comes handy to use boost::bind or the lambda expression is as predicate of the conditional version for the STL algorithms count_if and find_if.

We use count_if when we want to get the number of elements in a sequence that respect a clause we specify; find_if is used to find the fist element in a sequence matching our requirements.

Without using boost or C++11 we should define a functor to specify the behavior that we are interested in. As we can see in this example, the new techniques make the code cleaner and more readable:

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>

#include "boost/bind.hpp"

using namespace std;

namespace
{
   template<class T>
   void dump(vector<T>& vec)
   {
      copy(vec.begin(), vec.end(), ostream_iterator<T>(cout, " "));
      cout << endl;
   }
}

void bind04()
{
   vector<int> vec;

   vec.push_back(12);
   vec.push_back(7);
   vec.push_back(4);
   vec.push_back(10);
   dump(vec);

   cout << endl << "Using boost::bind" << endl;

   cout << "Counting elements in (5, 10]: ";

   // 1
   auto fb = boost::bind(logical_and<bool>(),
   boost::bind(greater<int>(), _1, 5),
   boost::bind(less_equal<int>(), _1, 10));
   int count = count_if(vec.begin(), vec.end(), fb);
   cout << "found " << count << " items" << endl;

   cout << "Getting first element in (5, 10]: ";
   vector<int>::iterator it = find_if(vec.begin(), vec.end(), fb);
   if(it != vec.end())
      cout << *it << endl;

   cout << endl << "Same, but using lambda expressions" << endl;

   cout << "Counting elements in (5, 10]: ";

   // 2
   auto fl = [](int x){ return x > 5 && x <= 10; };
   count = count_if(vec.begin(), vec.end(), fl);
   cout << "found " << count << " items" << endl;

   cout << "Getting first element in (5, 10]: ";
   it = find_if(vec.begin(), vec.end(), fl);
   if (it != vec.end())
      cout << *it << endl;
}
1. since we use the same predicate a couple of times it's a good idea storing it in a local variable (here using the cool C++11 'auto' keyword to save the time from figuring out the correct type definition for the predicate). The construct is a bit verbose, but should be clear enough in its sense: we are looking for a value in the interval (5, 10]; count_if will count all the elements in the sequence respecting this rule; find_if will return the iterator to the first element for which that is valid - or end() if no one will do.
2. it is so much cleaner implementing the same functionality using the C++11 lambda syntax.

The code is based on an example provided by "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. An interesting reading indeed.

Go to the full post

std::sort

To use the STL sort algorithm on a container, the type used by the container should define a less-than operator.

But what if we are required to order the container in different ways? We could pass to sort a predicate that defines our specific less-than operator.

If we are not using boost or C++0x usually this means we create a specific functor just for that.

Here we see an example to accomplish this task using boost::bind or a lambda expression:

#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>

#include "boost/bind.hpp"

using namespace std;

namespace
{
class PersonalInfo
{
string name_;
string surname_;
unsigned int age_;

public:
PersonalInfo(const string& n, const string& s, unsigned int age) :
name_(n), surname_(s), age_(age) {}

string name() const { return name_; }

string surname() const { return surname_; }

unsigned int age() const { return age_; }

// 1. define the operator less-than based on the first name
friend bool operator< (const PersonalInfo& lhs, const PersonalInfo& rhs)
{ return lhs.name_ < rhs.name_; }

};

// 2.
ostream& operator<< (ostream& os, const PersonalInfo& pi)
{
os << pi.name() << ' ' << pi.surname() << ' ' << pi.age() << endl;
return os;
}

void dump(vector<PersonalInfo>& vec)
{
copy(vec.begin(), vec.end(), ostream_iterator<PersonalInfo>(cout));
cout << endl;
}
}

void bind03()
{
vector<PersonalInfo> vec;
vec.push_back(PersonalInfo("Little", "John", 30));
vec.push_back(PersonalInfo("Friar", "Tuck", 50));
vec.push_back(PersonalInfo("Robin", "Hood", 40));
dump(vec);

cout << "Default sorting (by name):" << endl;
sort(vec.begin(), vec.end()); // 3.
dump(vec);

cout << "By age:" << endl; // 4.
sort(vec.begin(), vec.end(), boost::bind(
less<unsigned int>(),
boost::bind(&PersonalInfo::age, _1),
boost::bind(&PersonalInfo::age, _2)));
dump(vec);

cout << "By surname:" << endl;
sort(vec.begin(), vec.end(), boost::bind(
less<string>(),
boost::bind(&PersonalInfo::surname, _1),
boost::bind(&PersonalInfo::surname, _2)));
dump(vec);

cout << "Using Lambda, sorting by age:" << endl; // 5.
auto fa = [](PersonalInfo p1, PersonalInfo p2) { return less<unsigned int>()(p1.age(), p2.age()); };
sort(vec.begin(), vec.end(), fa);
dump(vec);

cout << "Using Lambda, sorting by surname:" << endl;
auto fs = [](PersonalInfo p1, PersonalInfo p2) { return less<string>()(p1.surname(), p2.surname()); };
sort(vec.begin(), vec.end(), fs);
dump(vec);
}

1. since we define the operator less-than for this class, it is possible sort its objects
2. let's the ostream know how to print it
3. first call to sort(), using the default less-than operator
4. let's use boost::bind to create a ordering predicate on the fly. We use the STL less functor passing it the two elements in the sequence that the sort algorithm provides
5. same as 4., but using C++0x lambda expressions. It is not necessary storing the lambda expression in a local variable, but it looks to me in this way the code is a bit more readable; and if you use the cool C++0x feature of type inference, by the keyword auto, it is neat and clear.

The code is based on an example provided by "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. An interesting reading indeed.

Go to the full post

Lambda for Fibonacci

I have found out an interesting example on an MSDN page that shows some lambda expression features.

I have reworked it a bit, and here you have the result:

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

namespace
{
    void dump(const std::vector< v)
    {
        std::for_each(v.begin(), v.end(), [](int n) { std::cout << n << ' '; }); // 1
        std::cout << std::endl;
    }
}

void fibonacci(size_t size)
{
    std::vector<int> vec(size, 1); // 2
    dump(vec);

    int base = 0; // 3 
    std::generate_n(vec.begin() + 2, size - 2, // 4
        [base, <vec]() mutable throw() -> int // 5
        {
            return vec[base++] + vec[base]; // 6
        });

    dump(vec);
    std::cout << base << std::endl; // 7
}
1. The first usage of a lambda expression here is not much interesting, it helps the for_each construct to output the vector elements to the console. The currently scanned element is assigned to the lambda parameter that is then used in the lambda body.
2. This vector is created using the size passed by the user, and initializing each of its values to one. Performance-wise this is not an optimal solution, but we can leave with it in this context.
3. in the variable base we keep the index of the first element in the vector that we need to get to calculate the next fibonacci value.
4. The generate_n() STL algorithm operates on a sequence, starting from the element pointed by the iterator passed as first parameter, iterating for the number of times passed as second parameter, applying the predicate specified as third parameter. It is here that we have an interesting lambda expression.
5. In the introduction clause we see the base variable passed by value, and the vec by reference. These variables will be accessible in the lambda body. The "mutable" specification means basically that the function local variable are copied to the lambda expression, so no change done there affect the original ones. The "throw()" clause tells that we are not supposed to throw any exception in the lambda expression. The "arrow" is actually the return type clause, in this case specifying that the lambda expression returns an int, in this case it is not mandatory, the compiler is smart enough to find out which type is the return value.
6. Notice that "base" is increased, this is the reason why we must specify this lambda expression as "mutable". By default you can't do that on a lambda by value parameter.
7. Here we'll see that the local "base" has not been changed.

Go to the full post