Re: standard vs. hand crafted loops
In article <1147114512.131883.144670@v46g2000cwv.googlegroups.com>,
<pavel.turbin@gmail.com> wrote:
I've seen many times advise to use standard loops e.g. for_each,
instead of iterator and for loop. I was trying to follow this hint.
But, it looks it involves extra complexity and the code getting larger
without any benefits for me.
for example: count length of each string wrapped into another object
(MyData):
I can't write anything more concise than the hand code loop using
just the standard library using std::accumulate which is more like what
you are doing it requires a binary functor,
This functor can be created inline with accumulate using either
boost::bind, or phoenix v1 below.
the binary functor can be created via boost[tr1] bind like this:
#include <iostream>
#include <ostream>
#include <boost/bind.hpp>
#include <vector>
#include <numeric>
#include <functional>
int main()
{
std::vector<std::string> data;
data.push_back("one");
data.push_back("four");
typedef std::string::size_type size_type;
size_type total = std::accumulate
(
data.begin(),
data.end(),
size_type(0),
boost::bind
(
std::plus<double>(),
_1,
boost::bind
(
&std::string::size,
_2
)
)
);
std::cout << "7 == "<< total << '\n';
}
or using phoenix 1.x in boost spirit library but it is independent of
spirit the functor can be created as:
#include <iostream>
#include <ostream>
#include <boost/spirit/phoenix.hpp>
#include <vector>
#include <numeric>
using namespace phoenix;
int main()
{
std::vector<std::string> data;
data.push_back("one");
data.push_back("four");
typedef std::string::size_type size_type;
size_type total = std::accumulate
(
data.begin(),
data.end(),
size_type(0),
arg1 + bind(&std::string::size)(arg2)
);
std::cout << "7 == "<< total << '\n';
}
the loop could be written as:
total = std::accumulate(data.begin(),data.end(),size_type(0),
arg1 + bind(&std::string::size)(arg2) );
which is almost as short and almost as readable as the hand coded loop.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]