Pages

Functor vs. lambda

Here is a good page on MSDN about lambda expressions in the C++0x flavor.

A first consideration is about comparing the usage of a functor and a lambda expression when is required to perform some operation on a sequence. In our case we would like to check how many elements in a vector of int are even. Here is a comparison between the two solutions:

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

using std::vector;
using std::cout;
using std::endl;
using std::for_each;

namespace
{
class EvenCount
{
int count_;
public:
explicit EvenCount() : count_(0) {}

void operator()(int n)
{
cout << n;

if(n % 2 == 0)
{
cout << " is even " << endl;
++count_;
}
else
cout << " is odd " << endl;

}

const int getCount() const { return count_; }
};

}

// Count the number of even numbers in a vector
void l03()
{
vector<int> vec;
for (int i = 0; i < 10; ++i)
vec.push_back(i);

// count using a functor
cout << "The even numbers in the vector are " <<
for_each(vec.begin(), vec.end(), EvenCount()).getCount() << endl;

// count using a lambda expression
int even = 0;
for_each(vec.begin(), vec.end(), [&even] (int n) {
cout << n;

if (n % 2 == 0)
{
cout << " is even " << endl;
even++;
}
else
cout << " is odd " << endl;
});

cout << "There are " << even << " even numbers in the vector" << endl;
}

In this case, chosing one solution or the other is basically a matter of taste. Most probably I would have taken the functor way here, since it looks to me a bit clearer.

But let's say I just had to count the even element, and not printing their single status to console. This would be the code resulting for the lambda expression:

// just counting with lambda
even = 0;
for_each(vec.begin(), vec.end(), [&even] (int n) { if(n%2 == 0) ++even; });
cout << "There are " << even << " even numbers in the vector" << endl;

I reckon it would not make much sense creating a functor, when we could write such a compact and clear piece of code instead.

Go to the full post

Lambda expressions in C++0x

A lambda expression is a way to implicitely define and construct a functor.

Here is a first example of its usage in C++0x:

#include <iostream>

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

void l01()
{
// no need to explicit the lambda return type in this case:
cout << [](int x, int y) { return x + y; }(4, 5) << endl;

// here the return type has to be explicited
cout << [](int x, int y) -> int { int z = x + y; return z + x; }(3, 5) << endl;
}

In the next example we see how a lambda expression could get access to one or all variable in the local scope, putting, as is said, them in the closure. Notice that if we don't prefix the variable in the closure with an ampersand, we access just a copy of the local variable.

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

using std::cout;
using std::endl;
using std::vector;
using std::for_each;

void l02()
{
vector<int> vec;
for(int i = 0; i < 10; ++i)
vec.push_back(i);

int total = 0;

// put 'total' as reference in the lambda closure
for_each(vec.begin(), vec.end(), [&total](int x) {total += x;});
cout << total << endl;

// put all the local variables as reference in the lambda closure
for_each(vec.begin(), vec.end(), [&](int x) {total += x;});
cout << total << endl;
}

Go to the full post

A boost::bind for any function

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

It's easy to use boost::bind for any function. Let's see an example where bind refers to a free function, a static member function, and a member function.

Notice that a member function could be called for an existing object, or we could create the object on the fly, and in this latter case we could use the nullary functor, that means, also the parameter for the object is passed directly as parameter to bind:

#include <iostream>
#include <string>
#include "boost/bind.hpp"

using std::string;
using std::cout;
using std::endl;
using boost::bind;

namespace
{
class AClass
{
public:
void printString(const string& s) const {
cout << "Member function: " << s << endl;
}

static void staticPrintString(const string& s) {
cout << "Static member function: " << s << endl;
}
};
}

void printString(const string& s)
{
cout << "Free function: " << s << endl;
}

void bind02()
{
bind(&printString, _1)("Hello!");

bind(&AClass::staticPrintString, _1)("Hello!");

AClass c;
bind(&AClass::printString, _1, _2)(c, "Hello!");

bind(&AClass::printString, AClass(), _1)("Hello!");

cout << "Nullary" << endl;
bind(&AClass::printString, AClass(), "Hello!")();
}

Go to the full post

Calling a member function via boost::bind and C++0x lambda

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

If your compiler is one that already supports the C++0x lambda, is probabibly better forgetting about boost:bind and using lambda (that is really cool). In any case, it is useful to know how to tackle a problem using different approach.

The following example shows how to call a member function inside a for_each call using the STL mem_fun_ref adaptor, boost::bind, and C++0x lambda:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include "boost/bind.hpp"

using std::string;
using std::cout;
using std::endl;
using std::vector;
using std::for_each;
using std::mem_fun_ref;
using boost::bind;

namespace
{
class status
{
std::string name_;
bool ok_;
public:
status(const string& name) : name_(name), ok_(true) {}
void breakIt() { ok_ = false; }
bool isBroken() const { return ok_; }
void report() const { cout << name_ << " is " << (ok_ ? "up" : "down") << endl; }
};
}

void bind01()
{
vector<status> statuses;
statuses.push_back(status("status 1"));
statuses.push_back(status("status 2"));
statuses.push_back(status("status 3"));
statuses.push_back(status("status 4"));

statuses[1].breakIt();
statuses[2].breakIt();

cout << "Using a classic for loop" << endl;
typedef vector<status>::iterator IT;
for (IT it = statuses.begin(); it != statuses.end(); ++it)
it->report();

cout << "Using for_each and mem_fun_ref" << endl;
for_each(statuses.begin(), statuses.end(), mem_fun_ref(&status::report));

cout << "Using for_each and boost::bind" << endl;
for_each(statuses.begin(), statuses.end(), bind(&status::report, _1));

cout << "Using for_each and C++0x lambda" << endl;
for_each(statuses.begin(), statuses.end(), [](status s){s.report();});
}

Go to the full post

boost::regex_token_iterator

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

Here is an example for regex_token_iterator (sregex_token_iterator the typedef for its std::string version) that shows how to use it for splitting a string accordingly to a specific regex:

#include <iostream>
#include <vector>
#include <string>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::ostream_iterator;
using boost::regex;
using boost::sregex_token_iterator;

void r07() {
regex reg("/");
string s = "Split/Values/Separated/By/Slashes";
vector<string> vec;

sregex_token_iterator it(s.begin(), s.end(), reg, -1);
sregex_token_iterator end;
while(it != end)
vec.push_back(*it++);

cout << s << endl;
copy(vec.begin(), vec.end(), ostream_iterator<string>(cout, " "));
}

Go to the full post

boost::regex_iterator

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

Instead of looping on regex_search to search all the occurrence of a regex in a string, we could use regex_iterator (or sregex_iterator for std::string) coupled with a for_each() call to scan the string.

Here is an example that scan in string all the comma separated numbers and then add them using a functor:

#include <iostream>
#include <string>
#include <functional>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using std::for_each;
using boost::regex;
using boost::sregex_iterator;
using boost::regex_search;

namespace
{
class Adder
{
int sum_;
public:
Adder() : sum_(0) {}

template <typename T> void operator()(const T& what)
{
sum_ += atoi(what[1].str().c_str());
}

int sum() const
{
return sum_;
}
};
}

void r06() {
regex reg("(\\d+),?");
string s = "1,1,2,3,5,8,13,21,34,55";

sregex_iterator it(s.begin(), s.end(), reg);
sregex_iterator end;

int sum = for_each(it, end, Adder()).sum();
cout << "summing " << s << ": " << sum << endl;
}

Go to the full post

boost::regex greedy and not

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

The regex (.*)(\d{2}) means something like: get all the character in the string (first expression) and then two decimal (second expression). The sensitive point is that the first expression is greedy, that means, it happily swallows as many couple of decimal as possible, leaving just the last one available for the second expression.

Sometimes this is not what we expect. Luckly we could modify the meaning of a expression making it not greedy just putting a question mark at its end: (.*?)

In this example we see this difference of behaviour in action:

#include <iostream>
#include <string>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using boost::regex;
using boost::smatch;
using boost::regex_search;

void r05()
{
smatch m;
string text = "Note that I'm 31 years old, not 32.";

cout << text << endl;

cout << "Greedy expression" << endl;
regex reg("(.*)(\\d{2})");
if(regex_search(text, m, reg))
{
if(m[1].matched)
cout << "(.*) matches: " << m[1] << endl;
if(m[2].matched)
cout << "(\\d{2}) matches: " << m[2] << endl;
}

cout << "Non-greedy expression" << endl;
reg = "(.*?)(\\d{2})";
if(regex_search(text, m, reg))
{
if(m[1].matched)
cout << "(.*) matches: " << m[1] << endl;
if(m[2].matched)
cout << "(\\d{2}) matches: " << m[2] << endl;
}
}

Go to the full post

boost::regex_replace

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

To replace all the occurences of a pattern in a string we could use the function regex_replace.

In the example is interesting noting that we create the regex using a flag to specify that it should be case insensitive (regex::icase). Notice that we should remember to or the flag to specify that we are using the default perl sintax for regular expression (regex::perl).

Other point of interest is that the string specified as replacement could be built from the regex itself, using the "$n" sintax. And this is useful in this case, since we want to preserve the original capitalization.

#include <iostream>
#include <string>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using boost::regex;
using boost::regex_replace;

int r04()
{
regex reg("(Colo)(u)(r)", regex::icase|regex::perl);

string s = "Colour, colours, color, colourize";
cout << s << endl;

s = regex_replace(s, reg, "$1$3");
cout << s << endl;
}

Go to the full post

boost::regex_search /2

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

In this example we use another overload of regex_search to scan a string to find how many elements of the passed regular expression are in it:

#include <iostream>
#include <string>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using boost::regex;
using boost::smatch;
using boost::regex_search;

void r03()
{
regex reg("(new)|(delete)");
smatch m;
string s = "Calls to new must be followed by delete. "
"Forgetting to call delete after a new results in a leak.";

cout << "Checking: " << s << endl;

int newNr = 0;
int delNr = 0;
string::const_iterator it = s.begin();
string::const_iterator end = s.end();

while(regex_search(it, end, m, reg))
{
if(m[1].matched)
{
cout << m[1] << " found, ";
++newNr;
}
if(m[2].matched)
{
cout << m[2] << " found, ";
++delNr;
}

// go on searching in the string
it = m[0].second;
}
cout << endl;

if(newNr == delNr)
cout << "Same number of new/delete in the string" << endl;
}

Go to the full post

boost::regex_search

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

Using regex_search we could check if a string cointains a regular expression.

The function requires in input the string to be searched, a match, and the regular expression.

A match is an object of this class:

template <class Iterator,
class Allocator=std::allocator<sub_match<Iterator> >
class match_results;

A few handy typedefs are available to simplify its usage. In the example we are about to use smatch, a match for a (simple) string.

Here is the example:

#include <iostream>
#include <string>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using boost::regex;
using boost::smatch;
using boost::regex_search;

void r02()
{
regex reg("(new)|(delete)");
smatch m;
string s = "Calls to new must be followed by delete.";

if(regex_search(s, m, reg))
{
if(m[1].matched)
cout << "(new), first expression in the regex, has been found" << endl;
}
}

Go to the full post

boost::regex_match

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

The function boost::regex_match() accepts in input a string and a boost::regex, and returns a boolean to show if the string matches the regular expression.

Here is a few examples:

#include <iostream>
#include <string>
#include "boost/regex.hpp"

using std::cout;
using std::endl;
using std::string;
using boost::regex;
using boost::regex_match;

void r01()
{
// 1.
regex reg("(A.*)");

bool b = regex_match("A", reg);
if(b)
cout << "Just an A is enough to match the regex A.*" << endl;

string s("This expression does not match with A.*");
b = regex_match(s, reg);
if(b == false)
cout << s << endl;

s = "As this string starts with A, it matches";
b = regex_match(s, reg);
if(b == true)
cout << s << endl;

// 2.
reg = "\\d{3}";
s = "Three and only thee digits are expected to match the regex ";
b = regex_match(s, reg);
if(b == false)
cout << s << reg << endl;

s = "123";
b = regex_match(s, reg);
if(b == true)
cout << s << " matches" << endl;

// 2bis.
s += " ";
b = regex_match(s, reg);
if(b == false)
cout << '\"' << s << "\" does not match" << endl;

// 3.
reg = "[a-zA-Z]+";
s = "Only a single word is expected to match the regex ";
b = regex_match(s, reg);
if(b == false)
cout << s << reg << endl;

s = "ThisI5NotGood";
b = regex_match(s, reg);
if(b == false)
cout << s << endl;

s = "ThisIsOK";
b = regex_match(s, reg);
if(b == true)
cout << s << endl;

// 3bis.
reg = "\\w*";
s = "Only a single word is expected to match the regex ";
b = regex_match(s, reg);
if(b == false)
cout << s << reg << endl;

s = "AWordCou1dContainNumber5";
b = regex_match(s, reg);
if(b == true)
cout << s << endl;

// 4.
reg = ".*";
s = "Anything (&%5^!) would match the regex ";
b = regex_match(s, reg);
if(b == true)
cout << s << reg << endl;

// 5.
reg = "\\d{2}|N/A";
s = "Only two digits or the string 'N/A' would match the regex ";
b = regex_match(s, reg);
if(b == false)
cout << s << reg << endl;

s = "42";
b = regex_match(s, reg);
if(b == true)
cout << s << endl;

s = "N/A";
b = regex_match(s, reg);
if(b == true)
cout << s << endl;

// 6.
reg = "\\d{3}[a-zA-Z]+.(\\d{2}|N/A)\\s";
s = "123BlahBlahBlah%88 ";
b = regex_match(s, reg);
if(b == true)
cout << '\"' << s << "\" matches " << reg << endl;

s = "123%88 ";
b = regex_match(s, reg);
if(b == false)
cout << '\"' << s << "\" does not match" << endl;

s = "123X%88 ";
b = regex_match(s, reg);
if(b == true)
cout << '\"' << s << "\" matches" << endl;

s = "123X%N/A ";
b = regex_match(s, reg);
if(b == true)
cout << '\"' << s << "\" ditto" << endl;

// 7.
reg = "\\d{3}([a-zA-Z]+).(\\d{2}|N/A)\\s\\1";
s = "123Hello!N/A Hello";
if(b == true)
cout << '\"' << s << "\" matches " << reg << endl;
}

1. means: any string starting with a capital A
2. three digits
3. a single word containing only alphabetic characters (at least one)
3bis. a single word containing alphanumeric characters
4. anything (even an empty string)
5. two digits, or the string "N/A"
6. collates 2., 3., a single character, 5., and finally a blank
7. same as 6. but it requires at its end the same first pattern in rounded parenthesis

Go to the full post

Regular expression with boost

As an introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing, and these are a few notes that I'm jotting down in the meanwhile.

The boost regex library is one of the few ones in that family that requires to be compiled and linked to our application to be used.

If you are using a popular compiler, boost provides makefiles and appropriate information to do that, have a look at the documentation for more details. In my current case, I'm using gcc and Code::Blocks as IDE. Once I generated the libs I set the project in the IDE in this way:

Through menu Project - Properties - button "Project's build options" - tab "Search directories" (for all the project configuration) - subtab "Compiler" add the base boost directory for the include files (in my case: "C:\dev\boost_1_40_0").

On the "Linker" subtab add the directory where we have generated the regex libraries (for me: "C:\dev\boost_1_40_0\libs\regex\build\gcc").

On the "Liker setting" tab we should now add the libraries, pay attention to insert debug and release version for the relative configuration.

Done that, we should just include the header file "boost/regex.hpp" to have access to the regular expression functionality.

A regular expression is created in our source code in this way:

boost::regex reg("(A.*)");

Now we have a (referenciabile) regular expression that is matching against any string starting with a capital A.

Go to the full post