standard vs. hand crafted loops
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):
=======================================================
class MyData // some object
{
std::string m_s;
public:
MyData( const std::string &s ) : m_s(s) {}
size_t len() const { return m_s.length(); }
};
class legngth // helper for for_each
{
size_t cnt; // accumulate result
public:
legngth(){ cnt = 0;} // initialize
void operator ()( const MyData &d) { cnt += d.len(); }
operator size_t() { return cnt; } // return the result
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<MyData> vec;
vec.push_back(MyData("a"));
vec.push_back(MyData("b"));
vec.push_back(MyData("c"));
//
// count length for all objects of "vec"
//
size_t l = 0;
// standard algorithm
l = std::for_each( vec.begin(), vec.end(), legngth() );
l = 0;
// hand crafted loop
for( std::vector<MyData>::iterator i=vec.begin(); i < vec.end();
++i)
l += i->len();
return 0;
}
=======================================================
Using for_each it takes 10 lines and auxiliary Function object. Compare
"for" loop it is only 3 lines. Such example looks as very common case,
it is typical to perform two or more operations on container. Create
function object looks as extra useless work.
Is there any better way to write such loops in general?
Thanks, Pavel
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]