Boost logo

Boost Users :

Subject: [Boost-users] [lambda] Making my expression less complicated
From: Peter Barker (newbarker_at_[hidden])
Date: 2008-09-05 12:30:42


Hello,

In my test program below, I have a container of columns and want to output the column headers into a string separated by a tab. The lambda expression is looking fairly complicated so I wonder if it could be made simpler or if there's any other algorithm I should've used to put a separator between the elements?

Regards,

Pete

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

#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/if.hpp>

class Column
{
public:
        explicit Column(const std::string& str) : str_(str) {}
        const std::string& getColumnText() const {return str_;}
private:
        std::string str_;
};

int main()
{

        using namespace boost::lambda;
        using boost::lambda::_1;

        std::vector<Column> cols;
        cols.push_back(Column("Fred"));
        cols.push_back(Column("Jim"));
        cols.push_back(Column("Harry"));
        const std::size_t numCols = static_cast<size_t>(cols.size());

        const char fieldSeparator = '\t';

        std::string outputText;

        std::size_t i = 1;
        var_type<std::size_t>::type iV(var(i));
        std::for_each(cols.begin(),cols.end(),
                (
                        var(outputText) += bind(&Column::getColumnText,_1),
                        if_then(iV < constant(numCols),var(outputText) += constant(fieldSeparator)),
                        ++iV
                )
        );

        std::cout << '[' << outputText << ']';
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net