Saturday, April 29, 2006

C++ : Exploring Sorting part III

I promised to talk about faster sorting algorithms and one of the fastest is the appropriately named quicksort. The algorithm was devised by British computer scientist in 1962! (I told you sorting was an age-old problem). His name is Charles Antony Richard Hoare his original paper is entitled C. A. R. Hoare. "Quicksort," Computer Journal, 1962, 5, p.p. 10-15. and is apparently still the most cited paper on the subject.

Anyway, I read an interesting article on searching (of which sorting is part of the solution) by Alexandrescu and the subject of this and the next blog is basically the good old "exercise for the reader" which I've done. I'm not going to claim that mine is the best or fastest implementation. In fact it performs alot slower the std::sort but there's always room for improvement and it's a good learning exercise. I have yet to completely finish tinkering with it so any suggestions would be welcome. I'd like to remove all recursion and make as many other speed improvements as possible. I also need to write a better testing framework with some proper profiling of the function. But anyway... here's the original quicksort algorithm expressed as a simple, non-generic function in C taken from Michael Lamont whose knowledge base pages have lots of nicely expressed C implementations of sorting algorithms with explanations and metrics


void quickSort(int numbers[], int array_size)
{
q_sort(numbers, 0, array_size - 1);
}


void q_sort(int numbers[], int left, int right)
{
int pivot, l_hold, r_hold;

l_hold = left;
r_hold = right;
pivot = numbers[left];
while (left < right)
{
while ((numbers[right] >= pivot) && (left < right))
right--;
if (left != right)
{
numbers[left] = numbers[right];
left++;
}
while ((numbers[left] <= pivot) && (left < right))
left++;
if (left != right)
{
numbers[right] = numbers[left];
right--;
}
}
numbers[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left < pivot)
q_sort(numbers, left, pivot-1);
if (right > pivot)
q_sort(numbers, pivot+1, right);
}



In part III we'll take this, make it generic as we did with the bubbleSort in Part II and use the ideas put forward by Alexandrescu to improve it's speed even further.

Friday, April 28, 2006

C++ : Exploring Sorting part II

In order to make our bubble sort function more generic (an thereby more useful) we could give it a function signature something along these lines:


template<class T>
void bubbleSort(T numbers[], size_t size);



This would mean we could call the function with an array of any type and the compiler would deduct the type to instantiate the function using the first parameter i.e.


float f[4] = {1.1f,0.2f,-2.3f,0.3f};
int i[4] = {6,3,1,5};
char *s = "zyxw"; // nicer syntax than...
//char s[4] = {'z','y','x','w'};

bubbleSort(f,4); // uses float
bubbleSort(i,4); // uses int
bubbleSort(s,4); // uses char



With the wonders of (take a deep breath) explicit template function argument specification we can do this now too...


bubbleSort<double*>(f,4); uses double



Even though we're using a float array the function is explicitly instantiated using the type double. This would compile fine but obviously yield a runtime error in this specific case because we'd be performing pointer arithmetic (i.e using the array) with a double type which is twice as big as the float parameter. But hang on a second... why does it even compile? You may have noticed something amiss here... we've used double* here explictly but when we don't specify the type i.e. bubbleSort(f,4) shouldn't the type of f be float and not float*? If this were true then our function would be written by the compiler thus:


// not what we get
void bubbleSort(float *numbers[], size_t size);
// this IS what we get!
void bubbleSort(float numbers[], size_t size);



The reason for this, and the reason why all the above code examples work is because when the compiler does type deduction it performs a number of type conversions on the actual type passed. If you want more details on this here's an excellent article by Angelika Langer on Function Template Arguments. I learnt alot reading this article. Jump to the section entitled "Implicit Type Conversions Involved in Template Argument Deduction" if you are just interested in what we've been talking about here, but I heartily recommend you read the whole thing. Anyway, I've got off the beaten track again, it's time to finish making our poor old, slow bubbleSort generic... aren't we done? No. It may work in it's current state for all POD (Plain Old Data) types but try this:


std::vector<int> array;
array.push_back(6);
array.push_back(3);
array.push_back(1);
array.push_back(5);

bubbleSort(array, array.size());



...and you'll quickly see it doesn't work for STL containers. You could always compile it and see why but put simply it's because we are asking the compiler to instantiate something along these lines:


void bubbleSort(std::vector<int> numbers[], size_t size);



Which is obviously ludicrous! Anyway, when we want to iterate though an STL container we don't pass the containers to algorithms but the containers iterator. I.e. std::swap(array.begin(), array.end());.

The iterator is an abstract concept, by that I mean that anything that behaves like an iterator is an iterator, including simple arrays. The reason why simple arrays are iterators too is because iterators are implemented using operator overloading of ++, --, [] among others (and depending on the type of iterator) to use the same syntax as pointer arithmetic. This gives us a clue as to how we can write our fully generic bubbleSort function. If we pass "pointers" to the start and end we can use pointer arithmetic inside the function body and it should work with both simple arrays and STL containers. One thing to note is that STL ranges are defined with a closed start and an open end. This means the begin() of an iterator points to the first element whilst the end() actually points to the element directly after the last element. This is something we need to be aware of when writing the function, luckily for us it is a really good design decision and greatly simplifies a lot of things for us! Anyway, I don't want to stray from the path of this blog anymore so perhaps we'll discuss STL ranges later, here's the final implementation of bubbleSort...


template<class Iter, class T>
void bubbleSort(Iter left, Iter right, T)
{
bool swap = true;
while(swap)
{
swap = false;
for(Iter it = left + 1; it!=right; ++it)
{
if(*it<*(it-1))
{
T tmp = *it;
*it = *(it-1);
*(it-1) = tmp;
swap = true;
}
}
}
}



However we can't use this function in exactly the same way as we use std::sort, it has 3 arguments! The first two specify the range we want to sort and the 3rd passes the type used in the container of the iterator! We need this to store our temporary variable T tmp = *it. Notice that there is no parameter variable specified as we only need to use the type. This makes the usage of this function pretty ugly:


//dereference first element to pass type of container
bubbleSort(array.begin(),array.end(),*array.begin());



No worries we can use explicit function template argument specification! (I hear you cry ... erm), well no we can't. We'd have to specify all the template arguments which would make the function quite tedious to use. A better solution is to write a simple function overload to call the above for us:


template<class Iter>
void bubbleSort(Iter left, Iter right)
{
bubbleSort(left, right, *left);
}



This is a neat trick we can use to quite clearly derive the container type of an iterator in a lot of situations.

To conclude this part we now have a more useful generic version of our algorithm which can by used for simple arrays and STL containers. The point of this blog has been to demonstrate how it's possible to convert an algorithm into a more useful, generic form. We'll look at some faster sorting algorithms in part III...

C++ : Exploring Sorting part I

Sorting is a fundamental requirement in many programs and libraries. As such it has been throughly explored by many people since the dawn of computers and there are many efficient algorithms and implementations available. This doesn't stop us pulling them apart, finding out all about them and seeing if we can't do better though! This is the first in a series of blogs on the subject where I want to go from looking at sorting algorithms to developing our own generic (of course!) sorting function.


I'll leave you with the good, old (and very, very slow) bubble sort ... we'll make it generic in part II...


void bubbleSort(int numbers[], size_t size)
{
bool swap = true;
while(swap)
{
swap = false;
for(int i = 1; i<size; ++i)
{
if(numbers[i]<numbers[i-1])
{
int tmp = numbers[i];
numbers[i] = numbers[i-1];
numbers[i-1] = tmp;
swap = true;
}
}
}
}

Tuesday, April 25, 2006

Retro Gaming : What's Knanshon?

Remember Xenon II : Megablast? At the start of every level you bought power ups and upgrades from this guy. One of them was called "Super Knanshon Power" which gave you every power-up and upgrade for the first 10 seconds. Not sure if it was spelt like this but it makes an excellent unique username for sure! :)

Friday, April 21, 2006

C++ : A response to functors

I received an interesting and detailed response to my posts on the uses of std::for_each from my friend Jun. Before we dive in I'd like to point out that I find it interesting that there seems to be an infinite number of ways of solving the same problem in C++! If you've ever used C# you'll know that the for(object in IEnumerable) syntax is part of the language. However this is a very different language despite the syntatical similarities and it doesn't do to pit one language against another ... they all have their uses.

Soapbox time over, let's get on with it!

Jun writes...

The thing I don't like about functors (function objects) is that they can clutter the code and they obscure the flow of the logic. Originally it is clear what you want - I only have to look at what you say is the ugly code (void B::Update()).

But I don't agree that the code has become easier to read or understand (i.e. maintain) toward the end of your article.

At the start it is clear that B has a container which is used to steer its controls.


In the end this simple piece of code is stretched out over a class A_UpdateHandler (it's Update function), B::Init() function and of course the B::Update() function. Undoubtfully the Init(), Update() and the A_UpdateHandler will end up apart from each other in the source file and it will become quite tricky for others (including yourself in a couple of months time) to piece out the flow of the code.

What happens when elements are added to or removed from m_APCollection after Init() has been called?


The design in the end is a workaround for the fact that C++ doesn't support Lambda calculus. If you look at it - the original Update() function is clear, but to be able to use std::for_each you had to create a functor and use a std::bind2nd with a std::mem_fun_ref which makes the end result more complex than what you originally started with.

I can imagine that if someone else would have to make a change to this code and allow for changes to be made to m_APCollection at runtime - (s)he could be in for a bind.


Everything in C++ is solvable by introducing an extra layer of indirection. But by doing so, simple things can be lost in the translation.

If you would use pseudo code to describe your algorithm it would be something like:


for a in m_APCollection do
control = GetControlByName ( a.GetName( ) )
if ( control ) then
graphic.doSomething( control.GetCurrentValue( )
> a.GetThreshhold( ) )
end
end

Now wouldn't it be nice to be able to stick as close to this as possible?

You definitely have to read FOREACH Redux by Niebler!
check this out:

BOOST_FOREACH ( char c, "Hello World" )
{
std::cout << ch;
}

or even

BOOST_FOREACH ( A *a, m_APCollection )
{
std::string const &name=a->GetName( );
Control *control = GetControlByName( name );
// can return NULL
if ( control )
{
bool value = control->GetCurrentValue( )
> a->GetThreshold( );
graphic.doSomething( value );
}
}

Sticks pretty close to what you originally intended? Then in turn it
is not that different from what you considered to be ugly code


Now I am curious if there is a way to force std::for_each in without having to write a wrapper and having to use "bind" and "mem_fun_ref".


How about this sneaky way to get access to that private function(compiles with the .NET C++ compiler - I haven't checked with GNU or others). No need to make changes to the interface and this is the update function:

void B::Update( )
{
Graphic const &graphic = GetGraphic( );
DoSomethingWithA functor(graphic, *this,
&B::GetControlByName);
std::for_each(mAPCollection.begin( ),
mAPCollection.end( ), functor);
}

(*disclaimer - I am not promoting this and any loss or
damage resulting from this code is your own responsibility!



Jun


So I agree with all of what is said here and have taken it on board. My main mistake in this case was the desire to use a tool that was unsuited to the task in hand. Having said that I learnt a lot so it is always recommended to try these things out! I actually managed to use a more straight forward functor without the pointer to a private member function hack to solve a similar problem after this and I think it made for much better code. Of the two solutions offered the BOOST_FOREACH is the most robust and readable. The Niebler article is well worth a read. Many good generic tricks are introduced in an interesting context and I learnt a lot. Especially the ScopeGuard trick from Alexandrescu ... but that's a topic for another post. The full code for Jun's own solution is shown below and I think you'll agree too that it is more readable and hence easier to maintain. The intention is clear and as it says in The Pragmatic Programmer "Program close to the Problem Domain".

#ifndef __B__H
#define __B__H

#include
#include

class A
{
public:
std::string const& GetName() const;
int GetThreshold() const;
};

struct Control { int GetCurrentValue() const { return 11; } };
struct Graphic { void DoSomething(bool) const {} };

class B
{
public:
void Update();
private:
Control const* GetControlByName(
std::string const &name) const;
Graphic const& GetGraphic() const;

std::vector mAPCollection;
};

#endif // __B__H


// b.cpp
#include "b.h"
#include

using namespace std;

string const& A::GetName() const
{
static string const name("Knanshon");
return name;
}

int A::GetThreshold() const { return 42; }

//--------------------------------------

namespace
{

class DoSomethingWithA
{
Graphic const &mGraphic;
B &mB;
typedef Control const* (B::*GetCtrl)
(std::string const&) const;
GetCtrl mFoo;
public:
DoSomethingWithA(Graphic const &graphic, B &b,
GetCtrl foo)
: mGraphic(graphic)
, mB(b)
, mFoo(foo)
{
}

void operator()(A *a)
{
string const &name=a->GetName();
Control const *ctrl=(mB.*mFoo)(name);
// can return NULL
if ( ctrl )
{
bool value = ctrl->GetCurrentValue() >
a->GetThreshold();
mGraphic.DoSomething(value);
}
}
};

} // anonymous namespace

//---------------------------------------------------

Control const* B::GetControlByName(
string const &name) const
{
return 0;
}

Graphic const& B::GetGraphic() const
{
static Graphic const g;
return g;
}

void B::Update()
{
Graphic const &graphic=GetGraphic();
DoSomethingWithA functor(graphic, *this,
&B::GetControlByName);
std::for_each(mAPCollection.begin(),
mAPCollection.end(), functor);
}

// eof

Thursday, April 20, 2006

C++ : Once false always false

I've recently written a useful little class that can be treated like a plain old bool type but has a couple of behavioural differences. It defaults to true on construction and once it is set to false, it can never be set to true. Here it is



class OnceFalseAlwaysFalse
{
public:
OnceFalseAlwaysFalse() : m_Value(true) {}
operator bool() { return m_Value; }
const bool operator ==(const OnceFalseAlwaysFalse &rhs)
{ return m_Value==rhs.m_Value; }
const bool operator !=(const OnceFalseAlwaysFalse &rhs)
{ return m_Value!=rhs.m_Value; }
const bool operator !(void)
{ return !m_Value; }
const OnceFalseAlwaysFalse &operator =(const bool & value)
{ if(m_Value) m_Value=value; return *this; }
private:
bool m_Value;
};


What the hell use is that? I hear you cry. Well, consider the following, fictitious example.



// Function to save as many pages as it can,
// returns false if any failed to print.
bool PrintDocument(void)
{
bool success = true;

if(!PrintPage(1))
success = false;
if(!PrintPage(2))
success = false;
if(!PrintPage(3))
success = false;

return success;
}


And this is the function using the OnceFalseAlwaysFalse class instead of a plain old bool...



bool PrintDocument(void)
{
OnceFalseAlwaysFalse success;
success = PrintPage(1);
success = PrintPage(2);
success = PrintPage(3);
return success;
}


A lot neater I think you'll agree. It takes out the multiple if tests needed to ensure that the overall success of the function is stored rather than simply the storing the success of the last operation. The class also illustrates one of Bjarne Stroustrups major intentions for the C++ language, i.e. that custom data types can be treated in exactly the same way as built-in types. This is achieved via the medium of operator overloading. For this class I have overloaded the =, !=, == and bool (implicit conversion to bool) operators. The last one is useful as it allows an instance of OnceFalseOnlyFalse to be returned by a function which is defined to return a bool, as many are.


Hope this can help you write some easier-to-read code!

Thursday, April 13, 2006

C++ : C++0x

http://www.artima.com/cppsource/cpp0x.html



Bjarne Stroustrup (the creator of C++) offers a sneak peek at the next version of standard C++ ("C++0x") which should be complete by 2009, and will then become C++09.

The current standard version is C++98, it takes along time to ratify these changes!

See my links on the sidebar for Bjarne Stroustrup's Homepage

Saturday, April 08, 2006

HTML : <pre><tt>y code

Well, in my first ever post to this blog I mentioned that I was trying to get the formatting to look good for my code examples. One of the easiest ways I found to do this in HTML was by using the <pre> tag. Any text between the <pre> and </pre> tags will not be formatted, i.e. wrapped or have whitespace stripped which your browser usually does. This is very handy for indented code.

One caveat is that you have to be careful to ensure the lines aren't too long. In this blog I ensure that a code line never exceeds column 67.

Ok, that takes care of the formatting, but how do I get a nice fixed width font for the code examples. Style-sheets! I hear you cry, and indeed they do come in very useful for exactly this kind of thing but there is a simpler way to achieve this common task in HTML, the <tt> tag. This stands for teletype. An easy-to-use tag it is much more suitable for writing code snippets in amongst the normal text. The alternative would be something like this: <div class="code"> and then you'd have to specify the styling, i.e. font etc. in a stylesheet - which, by the way, is the only place you should put style information - remember this simple rule:

HTML/XML = Content

CSS/XSL = Style


The two should always be seperate in any good system. Imagine having to go through every single one of your postings and changing them to conform to a style rather than simply changing the template and republishing!


Obviously you can still add additional styling for the <tt> tag if you wish. Indeed on this blog I have changed the font color slightly just to make the in place code snippets stand out a bit more.


I also enclose my large code examples in <blockquote>'s, which in my stylesheet/template is defined as having a darker background since this is how you'll find it done in most books written about code. Be careful to put the <blockquote> inside the <pre> and <tt> tags otherwise the darker blocks will extend to the top and bottom of the containing paragraphs and look ugly.


Anyway, if you have a blog of your own I hope this can help you have <pre><tt>ier text!


For a look at what a good stylesheet can do visit http://www.csszengarden.com/

C++ : In a bind with function objects part IV

Just to recap let’s look at the relevant parts of class B again in it’s entireity…


class B
{
public:
void Update()
{
Graphic &graphic = GetGraphic();

std::for_each(
m_A_UpdateHandlers.begin(),
m_A_UpdateHandlers.end(),
std::bind2nd(
std::mem_fun_ref(&A_UpdateHandler::Update),
&graphic)
);
}

private:
void Init()
{
Control *control;

for(APtrContainer::iterator it = m_APCollection.begin();
it!= m_APCollection.end(); ++it)
{
A &a = *it;
std::string &name = a.GetName();
control = GetControlByName(name);
if(control)
{
const int threshold = a.GetThreshold();
m_A_UpdateHandlers.push_back(
A_UpdateHandler(*control, threshold));
}
}
}


Control *GetControlByName(std::string);
Graphic &GetGraphic() const;
...
private:
APtrContainer m_APCollection;
A_UpdateHandlerContainer m_A_UpdateHandlers;
};


The first thing we notice is that design constraints imposed by the standard during the refactor have forced me to separate the processing of class A objects into an initialisation phase and an update phase. The potentially expensive call to GetControlByName is only done once per object in the initialisation phase as is the check to see if it returns a NULL value. Additionally, if the control indeed is NULL nothing gets added to the handler container. In the worst case, if no controls are found the update function will do nothing! Finally the update function in the handler that does the actual work is succinct and to the point, only expressing the minimum it needs to in order to get the job done. Everything required prior to this call has been handled already and is either passed in or cached where appropriate


void A_UpdateHandler::Update(Graphic *graphic) const
{
bool value = m_Control.GetCurrentValue() > m_Threshold;
graphic->doSomething(value);
}


All of these things have improved the code in terms of legibility, ease of maintenance and run-time efficiency, what more do you want!?


A couple of finer points are worth noting here before we end the last part in this series. std::bind2nd is obviously a templated function. The compiler implicitly deducts what types to use to instantiate the function using the types of the parameters. However, std::bind2nd defines the type of the second parameter as a reference type to this type. For this reason we must pass in a pointer to the Graphic object since references to references are illegal in C++ and your local friendly compiler will tell you as much if you attempt it! Also, when using std::mem_fun_ref in combination with std::bind2nd like this the member function must be const as std::bind2nd (and std::bind1st for that matter) don’t allow the use of non-const adaptors as parameters. In our case of using a wrapper class, which acts as a kind of functor with a constant state that we don’t need to change, this is not an issue, then again, there’s always that lovely keyword mutable.

Friday, April 07, 2006

C++ : In a bind with function objects part III

Given this constraint I needed to write a new member function for class A that did the work, at the time (luckily for me as it turned out) this wasn’t an option so I thought that this sounded like a job for a wrapper class!


class A_UpdateHandler
{
public:
A_UpdateHandler(Control &control, const int threshold)
: m_Control(control)
, m_Threshold(threshold)
{
}

void Update(Graphic *graphic) const
// want to pass this in as it doesn’t make
// sense for all the handler objects to
// store the same pointer
{
bool value = m_Control.GetCurrentValue() > m_Threshold;
graphic->doSomething(value);
}

private:
Control &m_Control;
const int m_Threshold;
};

typedef std::vector<A_UpdateHandler>
A_UpdateHandlerContainer;


Next I needed to create a collection of these handlers and initialise them. So a couple of (private) additions to class B did the trick.


class B
{

private:

void Init()
{
// Note: using a for-loop here to illustrate the current
// point more clearly, I’ll leave refactoring to a pref-
// erable implementation using for_each as an exercise
// for the reader! Clue: try using std::transform with
// a back_inserter.
// When I first came across this problem an Init member
// already existed in the real version of “class B”
// that iterated through the collection anyway,
// perhaps I should go back and refactor that too…

Control *control;

for(APtrContainer::iterator it = m_APCollection.begin();
it!= m_APCollection.end(); ++it)
{
A &a = **it;
std::string &name = a.GetName();
control = GetControlByName(name);
if(control)
{
const int threshold = a.GetThreshold();
m_A_UpdateHandlers.push_back(
A_UpdateHandler(*control, threshold));
}
}
}

private:
A_UpdateHandlerContainer m_A_UpdateHandlers;
};


Now class B’s update function can now be written using a call to std::for_each


void B::Update()
{
std::for_each(
m_A_UpdateHandlers.begin(),
m_A_UpdateHandlers.end(),
std::mem_fun_ref(&A_UpdateHandler::Update));
// we have a problem!
}


Another problem!! Oh no, but before we explore what it is an how I overcame it to get to the end of this refactor (finally!!) I’d like to point out the use of std::mem_fun_ref above. It does the same as std::mem_fun but works with a collection of references instead of pointers.


template<class Result, class Type>
std::mem_fun_ref_t<Result, Type>
std::mem_fun_ref(Result (Type::*pm)());


So, the problem with calling A_UpdateHandler::Update in this way is that there’s no way of passing the Graphic * parameter that we need - or is there? Enter that old favourite, std::bind2nd and the final update function looks like this:


void B::Update()
{
Graphic &graphic = GetGraphic();

std::for_each(
m_A_UpdateHandlers.begin(),
m_A_UpdateHandlers.end(),
std::bind2nd(
std::mem_fun_ref(&A_UpdateHandler::Update),
&graphic)
);
}


Which in terms of sheer aethestetics looks a lot prettier than our original for-loop! This isn’t mere triviality, in my experience elegant looking code usually indicates a more elegantly designed solution under the hood. There are several reasons why this is the case here.


... and I'll go through it with you in Part IV :)

C++ : In a bind with function objects part II

So, this was my first attempt at the function object...


class doSomethingWithA :
public std:unary_function<A *, void>
{
void operator() (A *a)
{
std::string &name = a->GetName();
// Oh No! GetControlByName is a member of class B!
Control *control = GetControlByName(name);
if(control)
{
// so can’t use control here
bool value =
control->GetCurrentValue() > a->GetThreshold();
graphic.doSomething(value);
// graphic comes from class B too!
}
}
};


When I started to write this function object I was feeling pretty proud of myself, but as they say, pride comes before a fall and I immediately fell over on the second line of the overloaded operator() method (i.e. the bit that gives an instance of this class function syntax making it a function object with the signature we want). There’s no way to call the methods I need as they are part of class B, the owner of this container. Ok, so I guess I need to pass in a reference to an object of class B?


Unfortunately, the methods of class B which I needed were declared private, so short of changing the accessibilty (shudder) of these I was pretty stuck. It was at this point that I begun to think that perhaps this std::for_each algorithm wasn’t very useful? After all my first version of Update() using a for-loop worked with no head scratching at all. Then again, for-loops themselves used to be a mystery once upon a time (really?) so on I soldiered.


Right, what to do? I did a quick bit of online research thinking that perhaps I could pass a member function of class B as the third parameter of std::for_each and found this useful little function adaptor:


template<class Result, class Type>
std::mem_fun_t<Result, Type>
std::mem_fun(Result (Type::*pm)());


Sounds like a jovial name doesn’t it? “Mem Fun” implies it does something amusing with memory but it actually stands for “Member Function”, this function takes a pointer to a member function and returns a function object. Just the ticket I thought so I rushed in and started to implement the member function of class B that could use all the lovely private methods and data it needed to. A quick glance at the usage of std::mem_fun and I realised my mistake:


class T
{
public:
T(int v) : m_v(v) {}
void print() const
{
cout << m_v;
}
private:
int m_v;
};

vector<T> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);

std::for_each(arr.begin(), arr.end(), std::mem_fun(&T::print));


Using std::mem_fun like this only works with a member function of the class you are using in std::for_each! This makes sense because in order to call a member function pointer you need an object as well and the only objects used in the std::for_each algorithm are the ones it gets from the first iterator parameter. Undeterred I had a sudden brainwave!


Find out what it was in part III

Thursday, April 06, 2006

First!

Welcome to Knanshon Coder's blog. I've recently written an article on the topic of C++ function objects and the std::for_each algorithm. I'll post it just as soon as I can get the formatting right in HTML from the original Word Document.

C++ : In a bind with function objects part I

So, here’s how it goes. I needed to perform an operation on each member of a list of pointers to class A. I’d always used for-loops to iterate though containers in the past. Also a lot of the functionality I needed in order to do the operation wasn't part of class A but of class B, which held the container of class A pointers as a member so this made sense. A little code may shed some light on things at this point:


class A
{
public:
std::string &GetName() const;
const int GetThreshold() const;
...
};

typedef vector<A *> APtrContainer;

class B
{
public:
void Update();

private:
Control *GetControlByName(std::string);
Graphic &GetGraphic() const;
...
APtrContainer m_APCollection;
};


Still, my desire to use std::for_each was strong, pah! to for-loops I thought, there must be a way!


I thought back to how the old, ugly code would have looked, something like this I guessed...


void B::Update()
{
Graphic &graphic = GetGraphic();

for(APtrContainer::iterator it = m_APCollection.begin(); it!=
m_APCollection.end(); ++it)
{
std::string &name = it->GetName();
Control *control = GetControlByName(name);
// can return NULL
if(control)
{
bool value =
control->GetCurrentValue() > it->GetThreshold();
graphic.doSomething(value);
}
}
}


So, now to refactor using std::for_each, I thought. I know I need to pass it a function object so let’s write that first. Perhaps I was being rash but fools rush in where angels fear to tread, so in I rushed …


Witness the resulting mess in part II coming soon...