Tidbits of Coding

I spend a large portion of my day coding. Mostly in C++ and Python. When working in C++ I try to make use of the Standard Template Library and Boost as much as possible to speed up development. If a GUI is needed, wxWidgets is usually the answer. However, combining all three of these things and making them speak to each other can be a bit cumbersome at times. So I try to rely on certain idioms or techniques that makes certain things more compact. Most of the time compactness leans less typing, sometimes it means that the code block is just easier to digest but a bit more typing.

This page has some examples of code that I've either used or just wondered about if it's possible to do. I don't advocate that they're the most efficient or the best way to solve the problems they represent, just examples of how I've learned to do certain things.

Fun with boost::integer_range

Fun with boost::integer_range
Lets say for some random reason you want to insert N integers into a std::vector using std::for_each and you want to do it using a range instead of a standard for loop. Maybe you just want to do it to see if you can.
#include <iostream>
#include <vector>

#include <algorithm>

#include <boost/lambda/lambda.hpp>
#include <boost/bind.hpp>
#include <boost/pending/integer_range.hpp>

int main( int argc, char **argv ) 
{

    std::vector<int>    MyVector;

    // insert values 0 to 9 into MyVector
    boost::integer_range<int> range(0, 10);

    std::for_each(  range.begin(), 
                    range.end(), 
                    boost::bind( &std::vector<int>::push_back, 
                                 &MyVector, 
                                 _1 ) );

    // output
    std::for_each(  MyVector.begin(), 
                    MyVector.end(), 
                    std::cout << boost::lambda::constant("Value: ") 
                              << boost::lambda::_1 
                              << boost::lambda::constant( "\n" ) );

    return 0;
}