Super-dee-duper D features

Michiel nomail at hotmail.com
Mon Feb 12 05:25:37 PST 2007


> The C++ version is even *worse* than the C one (for wordiness bother):
>
>  for (std::vector<T>::const_iterator i = e.begin(); i != e.end(); i++)
>  {  T v = *i;
>  ... }
>
> I mean I know the reasons for every bit of the syntax there, and in
> isolation they make sense, but put it all together and it seems to go
> backwards.

Hehe, sure. But that's like the worst possible way to do it. :)

* Most people make the std namespace public. Or at least the std::vector part.

* The variable i CAN be declared inside the loop, but it doesn't have to be. I
often do this at the beginning of a function. Granted, this doesn't make the
overall code smaller, but it does make it neater.

* Inside the loop, you rarely have to make a copy like you do. You can just use
i->member() or *i wherever you need them.

So it's actually:

for (i = e.begin(); i != e.end(); ++i) { ... }

Of course, the D foreach loop is still much neater (and I love it). But only if
you really want to visit all elements of an array in a row. However, if you want
to walk through two AA's at the same time (comparing keys and values, for
example), how do you do that in D? Maybe there is a way I haven't found yet (I've
only been working with D for a few weeks), but it looks to me like much more
bother than with C++ iterators.



More information about the Digitalmars-d mailing list