What to do after Python?

Johann Hibschman johann at physics.berkeley.edu
Mon Feb 19 02:04:51 EST 2001


First off, everyone, I'm sorry I opened my big fat mouth.
Now I'm just trying to run away gracefully.  :-)

Sheila King writes:

> :vector<double>::iterator end = vec->end();
> :vector<double> out(vec->size);
> :for(vector<double>::const_iterator i = vec->begin(),
> :    vector<double>::iterator j = out->begin();
> :    i != end;
> :    ++i, ++j) {
> :  *j = (*i)*(*i);
> :}

> I really don't understand that code, probably because I don't teach
> the STL. I can see that you're creating some new vector of doubles,
> called out, the same size as the vector vec.

Right.

> And for some reason, you're using two iterators to do your for-loop,
> though I can't see why.

Well, one's formally a constant iterator, and the other's not, so it
could be important if the vector vec were declared constant.
Likewise, it avoids having to call operator[] and doing the full
base+offset math, if we assume the compiler's not smart enough to
optimize the loop.


> To take the contents of one vector, and square each entry and put it in
> another vector, I would probably do this:

> apvector<double> out( vec.length());
> for ( int i= 0; i < vec.length(); i++)
>     out[i]= vec[i]*vec[i]

> I think that the code I list above is equivalent to yours?

Well, mine's a bit more efficient, since it doesn't have to maintain
the loop variable i, it doesn't have to call the function vec.length()
at each iteration, and it doesn't have to do the full operator[]
calculation.  It just steps along both of them.

But phooey on that!  It's bit-twiddling like that which drives me mad
while writing C++.  :-(


> My Python isn't that good, either. I haven't learned the lambda stuff, yet.
> Still, I never was claiming any sort of comparison between Python and C++.
> Matter of fact, I thought I said (in another message) that I really LIKE and
> sort of prefer Python. The question was, what is a good second language to
> learn. I don't see why C++ would be a bad choice, although I never argued in
> favor of it, either.

Again, I'm sorry, you just stumbled into a pet micro-managing
optimization peeve of mine, and I wasn't strong enough to resist
posting.


> vector<double> in;
> vector<double> out;
> :
> :
> :
> for (int i=0; i<in.size(); i++) 
>  out[i]=in[i]*in[i];

Yeah, that works.  I forget how the initialization checks for vector
work.  In addition, vector may even be checking each index i to see if
it's in range.  Etc.  In practice, most of my C++ code looks like
that, because the optimized way is just so ugly.

I'll be quiet now.

-- 
Johann Hibschman                           johann at physics.berkeley.edu



More information about the Python-list mailing list