Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Beef about using STL for_each vs. for-loop

2 views
Skip to first unread message

Fred Ma

unread,
Feb 23, 2003, 2:00:55 AM2/23/03
to
Hello,

If I use a for_each "loop" instead of a conventional
for loop, I have to encapsulate everything in a functor.
It doesn't matter how big or small the body of code
is, it needs its own functor definition (either that, or a
conventional function). Either way, I have to remove
the body of code far away from the site where I'll
be using it. I have to split it up like this even if I never
intend to use the functor/function for anything else. I
end up with many disparate snippets of functor code in
my header file, or in the cpp file. However, Meyers is a
strong proponent of using the for_each algorithm rather
than writing our own loops. Is there a clever way to
break down functionality of a program to avoid the
fragmenting of code that results from breaking code
segments into their own functors/functions? I tried
defining a function right within main itself, exactly at the
place where I want to use it; but it isn't apparently valid
C++.

Fred

John Gaughan

unread,
Feb 23, 2003, 2:23:06 AM2/23/03
to
> than writing our own loops. Is there a clever way to
> break down functionality of a program to avoid the
> fragmenting of code that results from breaking code
> segments into their own functors/functions? I tried

First of all, STL algorithms can help here. They cannot do everything,
but they cover all the basics. What they cannot do, a (hopefully) short
functor can. They do not have to be huge. You can place them somewhere
above or below the function you use them in with a forward declaration
wherever your prototypes are. This helps keep them out of the way. Or
you could write a few, put them in their own .cpp file and reuse them.
One of the tenants of OOP is code reuse ;-)

The advantage of for_each is that you can keep the loop small in terms
of the parent block, and as long as you comment it well and have a
descriptive functor name, it is quite readable. I do not see this as
code fragmentation, I see it as modularity. You separate the loop body
and create a module that can be reused elsewhere. How often do you have
redundant loops in your programs? I know I have them enough that I
probably should use for_each and functors more often.

John Gaughan
jo...@johngaughan.net

White Wolf

unread,
Feb 23, 2003, 2:26:31 AM2/23/03
to
"Fred Ma" wrote:
> If I use a for_each "loop" instead of a conventional
> for loop, I have to encapsulate everything in a functor.
> It doesn't matter how big or small the body of code
[SNIP]

> segments into their own functors/functions? I tried
> defining a function right within main itself, exactly at the
> place where I want to use it; but it isn't apparently valid
> C++.

It isn't because it is not "visible" for templates (has no external
linkage).

You need to use common sense. Only the knowledge of the concrete
problem can tell you if you need to use a for loop or a for_each.

Meyers suggests using for_each but we also know that it has its
drawbacks. One is the scattering you mention - but that is of course
rather an encapsulation or decoupling: you name a piece of code and you
do not care to share (or see in place) *how* it does it, only *what* it
does. Encapsulation and especially decoupling comes with a price. For
example a tight loop calling a non-inline function or functor (using
for_each for example) might get seriously slower than a for loop. Also
compilers are free to decide what do they inline and what not... So
IMHO the answer to the question is not so simple as: always use
for_each. You need to decide case by case.

WW


Anonymous

unread,
Feb 23, 2003, 2:37:32 AM2/23/03
to
"Fred Ma" <f...@doe.carleton.ca> wrote in message
news:3E5871A7...@doe.carleton.ca...

> Hello,
>
> If I use a for_each "loop" instead of a conventional
> for loop, I have to encapsulate everything in a functor.
> It doesn't matter how big or small the body of code
> is, it needs its own functor definition (either that, or a
> conventional function). Either way, I have to remove
> the body of code far away from the site where I'll
> be using it. I have to split it up like this even if I never
> intend to use the functor/function for anything else. I
> end up with many disparate snippets of functor code in
> my header file, or in the cpp file.

Just use a for loop. It's clearer, easier to write, and more
efficient.

> However, Meyers is a
> strong proponent of using the for_each algorithm rather
> than writing our own loops.

Maybe he should go back to making hot dogs.

White Wolf

unread,
Feb 23, 2003, 2:53:33 AM2/23/03
to
"Anonymous" wrote:
> Just use a for loop. It's clearer, easier to write, and more
> efficient.

Says who? When is this true?

> > However, Meyers is a
> > strong proponent of using the for_each algorithm rather
> > than writing our own loops.
>
> Maybe he should go back to making hot dogs.

Or you may take a bit down on your self-confidence slider?

What Meyers suggests is: "Prefer algorithm calls to hand-written loops".
Wow. He does not say: start and change them all etc. He says: prefer.
Which means (to me): first see if they fit only _then_ think about hand
written loops. You probably want to read the whole Item 43 in Effective
STL to get your facts right before you start ranting about a respected
author.

And next time make your insults using a real name or at least a real
email address. You know anonymous with a fake email address is cool for
an ftp server login but you have just lost all your credibility by
attacking someone and hiding your identity.

WW


Dimitris Kamenopoulos

unread,
Feb 23, 2003, 4:10:04 AM2/23/03
to
Fred Ma wrote:

> I tried
> defining a function right within main itself, exactly at the
> place where I want to use it; but it isn't apparently valid
> C++.

1) Don't use for_each if it is going to obscure your code, even Meyers
doesn't say anything different.
2) Although you cannot define functions inside functions, you can define
*functors* inside functions:

int main(){
...
class DoSomething{
void operator()...
};
...
for_each(...,...,DoSomething());


}

HTH,
Dimitris

White Wolf

unread,
Feb 23, 2003, 4:11:50 AM2/23/03
to
"Dimitris Kamenopoulos" wrote:
> 2) Although you cannot define functions inside functions, you can
define
> *functors* inside functions:
>
> int main(){
> ...
> class DoSomething{
> void operator()...
> };
> ...
> for_each(...,...,DoSomething());

I think you are wrong here. IIRC local classes does not have external
linkage and as such you cannot use them at template agruments. So ig
you want to hide things close, the best you can do is unnamed namespace.

IMHO those functors either should be templates (if they are generic
enough) or be static functions inside the classes scope. Of course,
with nice names it will add a lot the code's readability. Of course
only, if one realizes that for_each is not the only algorithm (we seem
to concentrate on that one here) and uses the right one. This last
assertion is in no way meant to be a reply to you - it just came into my
mind now.

WW


Fred Ma

unread,
Feb 23, 2003, 4:34:43 AM2/23/03
to
White Wolf wrote:

> "Fred Ma" wrote:
> > If I use a for_each "loop" instead of a conventional
> > for loop, I have to encapsulate everything in a functor.
> > It doesn't matter how big or small the body of code
> [SNIP]
> > segments into their own functors/functions? I tried
> > defining a function right within main itself, exactly at the
> > place where I want to use it; but it isn't apparently valid
> > C++.
>
> It isn't because it is not "visible" for templates (has no external
> linkage).
>
> You need to use common sense. Only the knowledge of the concrete
> problem can tell you if you need to use a for loop or a for_each.

Just to clarify....I wasn't suggesting that for_each be used
in all cases. I just wanted to benefit from the optimizations
that come with for_each (whatever they may be, as they are
surely implementation defined, though probably not container
defined else it would be a container-specific function like list::sort).

> Meyers suggests using for_each but we also know that it has its
> drawbacks. One is the scattering you mention - but that is of course
> rather an encapsulation or decoupling: you name a piece of code and you
> do not care to share (or see in place) *how* it does it, only *what* it
> does. Encapsulation and especially decoupling comes with a price. For
> example a tight loop calling a non-inline function or functor (using
> for_each for example) might get seriously slower than a for loop. Also
> compilers are free to decide what do they inline and what not... So
> IMHO the answer to the question is not so simple as: always use
> for_each. You need to decide case by case.
>
> WW

The fact that the better efficiency of for_each depends on the
implementation of the for_each makes it hard to judge which is
better. It might vary from library to library (right?). Though your
point about inlining is well taken. Til now, I just assumed that
anything that was templatized was inlined. It may have been a
wrong assumption, but what lead me to presume that was because
templates themselves don't represent concrete code until it is
instantiated with type/value specifications for the template
parameters. So I imagine the compiler stamping out an internal
concrete version of the template code at that point, and stuffing
it into the location where the template was invoked. Like a
#define, but less blindly and with much more sophistication.

Again, I see your point that the decision to use for_each shouldn't
be made blindly. If there was in fact a way to use it without
decoupling the code to some place far away (hard to do when I'm
using it in main), then it would certainly allow it to be sensibly used
in more situations. That way, I could benefit from the opaque and
potential speed advantage, even if I had no interest in making the
loop body into an separate, reusable piece of code. But it looks
like for_each was never meant to be used that way.

Fred

Fred Ma

unread,
Feb 23, 2003, 4:40:24 AM2/23/03
to
I forgot to add the following detail...

White Wolf wrote:

> > segments into their own functors/functions? I tried
> > defining a function right within main itself, exactly at the
> > place where I want to use it; but it isn't apparently valid
> > C++.
>
> It isn't because it is not "visible" for templates (has no external
> linkage).

I don't quite follow, but here's what I did:

int main(...){
...
double RtnDbl(void) { return 1.0+1.0; };
...
}

I didn't use templates, though I would tried have if the above
was accepted as legal. What I was trying to do was put the
functor definition close to the for_each loop in which it was
used.

Fred


White Wolf

unread,
Feb 23, 2003, 5:05:02 AM2/23/03
to
"Fred Ma" wrote:
> I don't quite follow, but here's what I did:
>
> int main(...){
> ...
> double RtnDbl(void) { return 1.0+1.0; };
> ...
> }
>
> I didn't use templates, though I would tried have if the above
> was accepted as legal. What I was trying to do was put the
> functor definition close to the for_each loop in which it was
> used.

IIRC it won't compile. First of all one cannot put function into
functions, that is sure. :-) And then if you put a local functor class,
that you cannot use with templates, since they "do not exist" for the
point of view of templates. They do not have external linkage.

WW


Fred Ma

unread,
Feb 23, 2003, 5:29:57 AM2/23/03
to
White Wolf wrote:

I just tried this in client.cpp:

typedef vector<int> vecint ;
typedef vector<vecint> vecvecint ;
int main ( int argc, char** argv){
......
vecvecint NetLstNum(/*Initialization argument*/); //
Simplified
struct PrntUniqNet : public unary_function<vecint,void>{
void operator()(vecint Net){
cout << Net ;
}; };
for_each( NetLstNum.begin(), NetLstNum.end(), PrntUniqNet() );
.......
};

Invoking g++ 3.2 from gvim gives the error (filtered through gSTLfilt and
manually prettified):

client.cpp|142| type `main(int, char**)::PrntUniqNet'
composed from a local is not a valid template-argument

client.cpp|142| trying to instantiate `template<_InputIter,
_Function>
_Function for_each(_InputIter, _InputIter, _Function)'

client.cpp|142| No match for
`for_each(vector<vecint>::iter, vector<vecint>::iter,
main(int, char**)::PrntUniqNet)'

Line 142 is the for_each "loop". So it looks like you're right.
The first error about a local being given as a template argument
smells alot like your point about no external linkages.

Fred

White Wolf

unread,
Feb 23, 2003, 5:45:06 AM2/23/03
to
"Fred Ma" wrote:
> Line 142 is the for_each "loop". So it looks like you're right.
> The first error about a local being given as a template argument
> smells alot like your point about no external linkages.

Yeah, it is a pity but that is how it works.

WW


Dimitris Kamenopoulos

unread,
Feb 23, 2003, 5:53:46 AM2/23/03
to
Fred Ma wrote:

> Line 142 is the for_each "loop". So it looks like you're right.
> The first error about a local being given as a template argument
> smells alot like your point about no external linkages.

Mea culpa, of course :-). Just keep the other advice: don't use for_each if
it's going to make your code too unreadable.

josh

unread,
Feb 23, 2003, 5:38:44 AM2/23/03
to
I hear you. I thought of this many times and found no acceptable solution, indeed you
end up with a pile of chunks of inner loops implemented as types that you're never
quite sure where they belong. If it truly feels awkward, just use the regular loop, I
guess; there's no need to enshrine "the STL way" of doing things. This is, imo, one of
the unfortunate ramifications, a weak point of the way the STL is designed.

White Wolf

unread,
Feb 23, 2003, 10:51:43 AM2/23/03
to
"josh" wrote:
> I hear you. I thought of this many times and found no acceptable
solution, indeed you
> end up with a pile of chunks of inner loops implemented as types that
you're never
> quite sure where they belong. If it truly feels awkward, just use the
regular loop, I
> guess; there's no need to enshrine "the STL way" of doing things. This
is, imo, one of
> the unfortunate ramifications, a weak point of the way the STL is
designed.

Or a weak understand of your about its design? At least those who
designed the standard library do not top post...


Fred Ma

unread,
Feb 23, 2003, 1:00:28 PM2/23/03
to
josh wrote:

> I hear you. I thought of this many times and found no acceptable solution, indeed you
> end up with a pile of chunks of inner loops implemented as types that you're never
> quite sure where they belong. If it truly feels awkward, just use the regular loop, I
> guess; there's no need to enshrine "the STL way" of doing things. This is, imo, one of
> the unfortunate ramifications, a weak point of the way the STL is designed.

Thanks for confirming that I'm not the only
one finding this awkward. I wouldn't personally
call it a weakness of STL's design, as I'm new to
STL and there's alot about how to best exploit
it which I am just becoming aware of. From the
responses so far, including yours, maybe for_each
was only intended to be used for certain situations.
The only reason I brought up my question was in
hopes of exploiting the efficiencies of using for_each
over hand crafted loops, as mentioned in Meyer's
book (though he did say that it isn't written in stone).
As I mentioned in prior posts, it's hard to know when
these efficiencies are being had because that involves
knowing the implementation details of for_each. Oh
well, for-loop, get ready.

Fred

josh

unread,
Feb 23, 2003, 4:35:06 PM2/23/03
to
Forgot to take your medications again, huh.

John Ericson

unread,
Feb 23, 2003, 9:39:39 PM2/23/03
to
"Anonymous" <nob...@nowhere.com> wrote in message
news:0T_5a.10255$ep5....@nwrddc02.gnilink.net...

> "Fred Ma" <f...@doe.carleton.ca> wrote in message
> news:3E5871A7...@doe.carleton.ca...
<<snip>>
> >...I have to encapsulate everything in a functor.

> Just use a for loop. It's clearer, easier to write, and
more
> efficient.
>
> > However, Meyers is a
> > strong proponent of using the for_each algorithm rather
> > than writing our own loops.
>
> Maybe he should go back to making hot dogs.
>

To be fair, Scott Meyers ("Effective STL" Item 43)
specifically says if you're doing something simple that
would require writing a functor or making a cluttered mess
of binders and adapters, then you are better off writing the
loop. I think Meyers would agree you should go with the for
loop under those circumstances. The efficiency of if we're
talking about execution speed AFAIK should favor for_each,
if anything . Apologies to Scott if I'm misquoting...

Best Regards, John E.


Nom De Plume

unread,
Feb 23, 2003, 10:31:23 PM2/23/03
to
Fred Ma <f...@doe.carleton.ca> wrote in message news:<3E590C3B...@doe.carleton.ca>...

> Thanks for confirming that I'm not the only
> one finding this awkward. I wouldn't personally
> call it a weakness of STL's design, as I'm new to
> STL and there's alot about how to best exploit
> it which I am just becoming aware of.

There is a great benefit in using algorithm template
functions for loops in theory, however, as with
most of the algorithm functions they are largely
compromised by lack of quality support in the language.

In comp.lang.c++.moderated (and the standard group)
I argued for a language modification to aleviate
this shortcoming, and it was generally agreed that
something along these lines needs to be done.

To summarize, it would work like this:

int sumInts(vector<int>& v)
{
int sum = 0;
for_each(v.begin(), v.end(), sum,
inline (int i, int& sum)
{
sum += i;
});
return sum;
}

Here I have embedded a function definition in as
an expression (a parameter to for_each). I have
also extended for_each to include an auxiliary
parameter to pass through to the function.

Clearly this is much easier than the mess of functors.
(Functors are, IMHO, simply a hack to get around
the lack of support for this in C++. That is almost
the only thing they are really used for.)

You can read the threads over there if you want more
detail (search for me on deja.com and you should find
a bunch of stuff.)

However, since this is not supported currently, there
is a very limited alternative you might consider:

int sumInt(vector<int>& v)
{
struct S {
static void summer(int i, int& sum)
{ sum+= i; }
};
int sum = 0;
my_for_each(v.begin(), v.end(), sum, S::summer);
return sum;
}

Here we have to define my_for_each to include the
extra parameter, viz:

template<class _InIt,
class _Fn1, class T> inline
_Fn1 for_each(_InIt _First, _InIt _Last, T& t, _Fn1 _Func)
{ // perform function for each element
for (; _First != _Last; ++_First)
_Func(*_First, t);
return (_Func);
};

Ugly, perhaps, but it gets us a step closer to a usable
algorithm class.

Lets just for a moment also discuss the motivation for
all this. The reasons why it is wise to use a predefined
algorithm like for_each include at least the fact that
it won't have any bugs, and also it may be better written
in terms of performance.

Performance imporvement is not intrinsic, just common.
For example,

for(int i=0; i < v.size(); ++i)
sum+= v[i];

Most likely will not be as fast as:

for(vector<int>::iterator p=v.begin(); p!=v.end(); ++p)
sum+=*p;

Because using iterators eliminates the extra expense
often associated with indexing an array.

However, a good coder can easily rewrite the first for loop
to use pointers rather than indexing. The main benefit of
the algorithm classes is that you can be sure they are correct
without all the off by one errors etc that are all to common.

However, since the language doesn't provide adequate support
for embedded statements within these algorithms it has lead
to all sorts of ugly macinations with stuff out of <functional>
which is so hard to get right that the fundamental benefit:
easy, bug free code, disappears down the toilet of
less< mem_fn <plus........

But that is just my opinion.

White Wolf

unread,
Feb 23, 2003, 11:14:52 PM2/23/03
to
"josh" wrote:
> Forgot to take your medications again, huh.

Nope. I just love newbies who make immediate decision that the STL is
badly designed but can spend a week to convert a loop to recursion... I
am taking my medications. One pill for heartburn one for arthritis.
How about you? Do you take the one for too high self confidence?

WW


Fred Ma

unread,
Feb 23, 2003, 11:16:30 PM2/23/03
to
Nom De Plume wrote:

Yes, that's what I was dreaming about after falling
asleep at the keyboard. But really, it's starting to
look very much like a for loop.

> Clearly this is much easier than the mess of functors.
> (Functors are, IMHO, simply a hack to get around
> the lack of support for this in C++. That is almost
> the only thing they are really used for.)

[snip]

Yes, I agree. But I wonder how many bugs can you
have in setting up your own for loop. I mean, not a
for loop that necessarily uses array indexing, as you
illustrate below, but one that increments an iterator
to step through all the container elements. Hmm. I
see that you get to that point below....

> Performance imporvement is not intrinsic, just common.
> For example,
>
> for(int i=0; i < v.size(); ++i)
> sum+= v[i];
>
> Most likely will not be as fast as:
>
> for(vector<int>::iterator p=v.begin(); p!=v.end(); ++p)
> sum+=*p;
>
> Because using iterators eliminates the extra expense
> often associated with indexing an array.

> However, a good coder can easily rewrite the first for loop
> to use pointers rather than indexing. The main benefit of
> the algorithm classes is that you can be sure they are correct
> without all the off by one errors etc that are all to common.
>
> However, since the language doesn't provide adequate support
> for embedded statements within these algorithms it has lead
> to all sorts of ugly macinations with stuff out of <functional>
> which is so hard to get right that the fundamental benefit:
> easy, bug free code, disappears down the toilet of
> less< mem_fn <plus........

If that's the case, then it seems like writing your own
for-loop (efficiently) isn't such an unattractive option
after all. The only thing I worry about (maybe needlessly)
is that there are optimizations that go deeper than the
efficient for-loop shown above. For example, I have no
idea what kind of data structure underlies the iterators
for the associative container classes, neither should I
have to reverse engineer it (that's the whole point of
object oriented). But the library designers can certainly
take advantage of those under-the-hood details.

But as you suggested, expediency and simplicity of
code may make it more attractive to write your own
loop anyway. Right now, I'm not battling the one-off
index errors that for_each would save me from. I'm
battling interfacing to external apps. When the time
comes where I *do* find myself spending my time
with the one-off errors in indexing, I may see things
differently.

Fred

Terje Slettebø

unread,
Feb 24, 2003, 6:41:49 AM2/24/03
to
nde_...@ziplip.com (Nom De Plume) wrote in message news:<b59f4084.03022...@posting.google.com>...

> Fred Ma <f...@doe.carleton.ca> wrote in message news:<3E590C3B...@doe.carleton.ca>...
> > Thanks for confirming that I'm not the only
> > one finding this awkward. I wouldn't personally
> > call it a weakness of STL's design, as I'm new to
> > STL and there's alot about how to best exploit
> > it which I am just becoming aware of.
>
> There is a great benefit in using algorithm template
> functions for loops in theory, however, as with
> most of the algorithm functions they are largely
> compromised by lack of quality support in the language.
>
> In comp.lang.c++.moderated (and the standard group)
> I argued for a language modification to aleviate
> this shortcoming, and it was generally agreed that
> something along these lines needs to be done.
>
> To summarize, it would work like this:
>
> int sumInts(vector<int>& v)
> {
> int sum = 0;
> for_each(v.begin(), v.end(), sum,
> inline (int i, int& sum)
> {
> sum += i;
> });
> return sum;
> }

How about:

int sum=0;
std::for_each(v.begin(), v.end(), sum+=_1);

It doesn't get much simpler than this. :)

No need to change C++, no need for a new for_each, it's all possible
in C++98. :) It's also shorter than your suggestion.

Example:

#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp> // Note

using namespace boost::lambda;

int main()
{
int array[]={1,2,3,4};

int sum=0;

std::for_each(array,array+4,sum+=_1);

std::cout << sum << '\n'; // Prints "10"
}

I've tested the above on Intel C++ 7.0, and it works.


Regards,

Terje

tslettebo at chello no

Terje Slettebø

unread,
Feb 24, 2003, 6:58:27 AM2/24/03
to
nde_...@ziplip.com (Nom De Plume) wrote in message news:<b59f4084.03022...@posting.google.com>...

By the way, here's a link to Boost.Lambda, used in my previous posting
(http://www.boost.org/libs/lambda/doc/index.html).

Terje

Dietmar Kuehl

unread,
Feb 24, 2003, 8:01:25 AM2/24/03
to
Fred Ma <f...@doe.carleton.ca> wrote:
> Is there a clever way to
> break down functionality of a program to avoid the
> fragmenting of code that results from breaking code
> segments into their own functors/functions?

Just a few random notes on this general topic:

- There is a pretty clever library available at Boost which allows use of
pretty advanced expressions as functors. I think it's the lambda library.
It is not a solution to everything but addresses many of the small
functors.

- Use of algorithms expresses more clearly what you want to do, hiding the
details how it is actually done. Writing idiomatic and self documentating
code can easily return the cost of separating the code fragments. Whether
algorithms are applicable depends, however, on what you are doing.

- Since optimizations for algorithms like 'for_each()' where mentioned:
Well, there are indeed optimizations even for algorithms like 'for_each()'
but only relatively minor ones, ie. these only pay off if the algorithm is
executed one long sequences and the functor only does very few operations.
Particularily for 'for_each()' I'm only aware of loop unrolling and the
segmented sequence optimization both aiming at reducing the costs of
incrementing and checking the iterators - actually a relatively desparate
attempt at squeezing performance out of the loop.
--
<mailto:dietma...@yahoo.com> <http://www.dietmar-kuehl.de/>
Phaidros eaSE - Easy Software Engineering: <http://www.phaidros.com/>

josh

unread,
Feb 24, 2003, 6:02:17 AM2/24/03
to
No, no pills, none of this sophisticated stuff. I maintain a good health by watching
prodigious amounts of porn, beats the C++ Standard hands down. If you wanna swap
movies, let me know... ("White Wolvz and Black Bitchz!!! (In Heat Interracial #9")...
that's one for_each loop everyone's gonna like! We could use this ng to review the
videos, I hope it's not off topic so long as we don't top-post).


Nom De Plume

unread,
Feb 24, 2003, 11:58:06 AM2/24/03
to
Fred Ma <f...@doe.carleton.ca> wrote in message news:<3E599C9D...@doe.carleton.ca>...

> But as you suggested, expediency and simplicity of
> code may make it more attractive to write your own
> loop anyway.

However the equation changes when you have access
to the anonymous inline definition of functions,
and you learn all the juicy functions there are
in algorithms. For example, I recently needed to
fill an array with ascending values, 1, 2, 3 etc.

void fillValues(vector<int>& v)
{
int counter = 0;
std::fill(v.begin(), v.end(), counter,
inline void (int& vectorVal, int& counter)
{
vectorVal = counter++;
});
}

By using the std algorithm here not only do I get
bug free, potentially efficient code, but I also
clearly document what I am trying to do: fill the
vector with values.

if you went the more regular route, you don't have
the advantage of the name "fill" in there, the code
reader has to work it out.

Consider also:

struct Employee {string name; int empId;};

void sortEmployees(vector<Employee>& employees)
{
std::sort(employees.begin(), employees.end(),
inline bool(Employee& lhs, Employee& rhs)
{
return (lhs.name == rhs.name
&& lhs.empId < rhs.empId)
|| lhs.name < rhs.name;
});
}

In this case the sorting criteria (first by name then
by empId) is immediately apparent to the reader of the
code.

There are many, many useful functions in algorithm
that are just begging to be used, however lack of
language support for something along the lines proposed
above, severely handicaps their usefulness.

White Wolf

unread,
Feb 24, 2003, 1:06:45 PM2/24/03
to
"josh" wrote:
> On Mon, 24 Feb 2003 06:14:52 +0200, "White Wolf" <wo...@freemail.hu>
wrote:
> > "josh" wrote:
> > > Forgot to take your medications again, huh.
> >
> > Nope. I just love newbies who make immediate decision that the STL
is
> > badly designed but can spend a week to convert a loop to
recursion... I
> > am taking my medications. One pill for heartburn one for arthritis.
> > How about you? Do you take the one for too high self confidence?
> No, no pills, none of this sophisticated stuff. I maintain a good
health by watching
> prodigious amounts of porn, beats the C++ Standard hands down.

Now I get it. Well, have a good movie night then.

> If you wanna swap movies, let me know...

Well, no thanks. I do not have such movies. I am rather a practicing
type.

> ("White Wolvz and Black Bitchz!!! (In Heat Interracial #9")...
> that's one for_each loop everyone's gonna like! We could use this ng
to review the
> videos, I hope it's not off topic so long as we don't top-post).

Since I do not have enough data to find out if this is another infantile
insult or a bad joke I will treat it as the latter - as the netiquette
says. :-)

WW


Nom De Plume

unread,
Feb 24, 2003, 1:54:05 PM2/24/03
to
terjes.@chello.no (Terje Slettebř) wrote in message news:<9e3a34f7.03022...@posting.google.com>...

> How about:
>
> int sum=0;
> std::for_each(v.begin(), v.end(), sum+=_1);
>
> It doesn't get much simpler than this. :)

No indeed. But it also doesn't get much more complicated
that that. Lambda is a pretty cool piece of work, however
it too limited in its applications. Anything above an
expression is too hard for lambda, and that is frequently
not good enough. C++ is not a functional language, so many
program structures that we might want cannot be reduced
to expressions (or cannot be so reduced in a clear and
efficient manner.)

No doubt it is a tour de force of template hacking,
and no doubt it is cool as anthing I have seen, but
it doesn't address all the problems that a well crafted
anonymous function structure would.

White Wolf

unread,
Feb 24, 2003, 2:04:25 PM2/24/03
to
"Nom De Plume" wrote:
> No doubt it is a tour de force of template hacking,
> and no doubt it is cool as anthing I have seen, but
> it doesn't address all the problems that a well crafted
> anonymous function structure would.

And I hope (since boost people *are* around the standard) that those
things will be addressed. IMHO what I miss the most from C++
(sometimes) is the simplicity of code blocks in CA-Clipper and the RAII
variables in there. I do not miss the GC but I miss language support
for PIMPL. And of course language support for "iterating templates",
templates with multiple arguments repeating the output code. Very much
like the thing Loki or Emily Winch does when they iterate through
members of a class. Serialization (or call whatever non-MS term) and
many other things could be done so much easier. I also miss
standardized runtime debugging support, such as "overloading" the
throw/functionality keyword etc. (It might be that at some point I want
to crash on throwing a specific exception.) Anyways the lamba is
something very similar to those missing dynamic features. But to get
there is way too difficult.

WW


josh

unread,
Feb 24, 2003, 10:14:53 AM2/24/03
to
Cool. :-)

Fred Ma

unread,
Feb 24, 2003, 5:31:44 PM2/24/03
to
Nom De Plume wrote:

Yeah, that would look kind of handy to use, that form
of stepping through the container.

Fred


Alan Krueger

unread,
Feb 25, 2003, 3:43:02 PM2/25/03
to
"Fred Ma" <f...@doe.carleton.ca> wrote in message
news:3E58A2A4...@doe.carleton.ca...

> typedef vector<int> vecint ;
> typedef vector<vecint> vecvecint ;
> int main ( int argc, char** argv){
> ......
> vecvecint NetLstNum(/*Initialization argument*/); //
> Simplified
> struct PrntUniqNet : public unary_function<vecint,void>{
> void operator()(vecint Net){
> cout << Net ;
> }; };
> for_each( NetLstNum.begin(), NetLstNum.end(), PrntUniqNet() );
> .......
> };

Honestly, the for_each here is going to contribute less to unreadability
than the excessive abbreviations. Changing NetListNum (or NetLastNum, or
NetLostNum, can't tell which!) to NetLstNum only saves a single character
but becomes MUCH more unreadable.

Your code should convey meaning, not just be functional, if you ever hope to
easily maintain it in the future.

Alan Krueger

unread,
Feb 25, 2003, 3:45:16 PM2/25/03
to
"White Wolf" <wo...@freemail.hu> wrote in message
news:b3c65b$chi$1...@phys-news1.kolumbus.fi...

> "josh" wrote:
> > Forgot to take your medications again, huh.
>
> Nope. I just love newbies who make immediate decision that the STL is
> badly designed but can spend a week to convert a loop to recursion...

Or believe they can roll their own, better implementation, but can't quite
get it to compile properly.

White Wolf

unread,
Feb 25, 2003, 4:44:39 PM2/25/03
to
"Alan Krueger" wrote:
> > "josh" wrote:
> > > Forgot to take your medications again, huh.
> >
> > Nope. I just love newbies who make immediate decision that the STL
is
> > badly designed but can spend a week to convert a loop to
recursion...
>
> Or believe they can roll their own, better implementation, but can't
quite
> get it to compile properly.

Yeah. Those damn compilers. :-)


Fred Ma

unread,
Feb 26, 2003, 12:33:03 AM2/26/03
to
Alan Krueger wrote:

There's more comments in the real program. I've stripped it out
to present a toy problem. Also, it's a circuit design program,
so there's more context than shown in the example.

I also have a personal preference for narrow linewidths, which
naturally causes me to abbreviate. I try to compensate with comments.

Fred


f

unread,
Feb 28, 2003, 11:22:59 AM2/28/03
to
terjes.@chello.no (Terje Slettebř) wrote in message news:<9e3a34f7.03022...@posting.google.com>...

Thanks, Terje. I took a look at some Boost stuff
before. It is certainly an intriguing collection
that I have to spend more time playing with. Now
is kind of hectic, so it will happen a bit further
into the future.

Fred

0 new messages