There are plenty of resources on how we may recursively search and print the contents of binary trees. This example shows how to (recursively) make use of the Boost serialization libraries and streams in order to print the contents of a tree-like data structure.
For another example posts on functors (function objects) see here. A functor is an instance of a C++ class that has the
operator() defined. One big advantage of functors is that when you define the
operator() in C++ classes you not only get objects that can act like functions, but can also store state as well.
Some code samples I have collated in the sample below, that demonstrate how
boost::function can be assigned with functors, ordinary functions, class member functions and overloaded class member functions respectively.
This post takes a look at using
boost::bind as a means of calling class
member functions in an efficient and generic way. It basically summarizes what has
already been said at Björn Karlsson’s excellent Informit article. Since I found the post useful, I thought it worth reproducing here, using the same
status class but containing all the examples and approaches he describes in one program. Continue reading
A summary with code samples of the set operations that come with STL: union, intersection, symmetrical difference and set difference.
For consistency, the two sets of integer vectors used in each example are the same and are: Continue reading
A generic Print function
A way of using STL algorithms combined with template functions as a means of printing the contents of any type of STL container (eg a
std::vector), containing any generic data type (eg
typename T defines the generic data type held by the container, while
typename InputIterator describes the STL container iterators passed to it:
By definition you cannot sort a
std::map by value, since a
std::map sorts its elements by key.
This posting documents a way to get around this by dumping
std::map key-value pairs into a
std::vector first, then sorting that
std::vector with a less-than functor afterwards
A short posting demonstrating how to remove the const-ness of a
const_iterator, given that it is not possible to use re-casting along the lines of
const_cast<> to convert from
Consider the following example:
Following on from the previous post, this example shows an example of how to use an STL multimap to track the line number(s) associated with each word in a text file.
This post aims to illustrate the power of using STL’s associative arrays as a word counter. It reads the entire contents of the text file, word-by-word, and keeps a running total of the number of occurences of each word. All using just a few lines of code, discounting the bits that output the results.