[LC++]STL Iterators and integers

Mark Phillips mark at austrics.com.au
Mon Aug 6 11:26:07 UTC 2001


Jack Lloyd wrote:

> >Doesn't it mean one addition _and_ one multiplication?  Ie,
> >
> >  address = base_address + i*sizeof(string)
>
> Yes, nominally. However, sizeof() is a compile time constant. So, basically,
> don't worry about it. The compiler will just scale your i value appropriatley,
> and there won't be any multiplications at run time.

I don't understand how it will scale i.  Sure it knows sizeof(string) at
compile time, but it doesn't know i until runtime, indeed, i varies at
runtime --- so surely a multiplication must be performed at
runtime???  I must be missing something.  The only thing I can think
of is that if sizeof(string) is a power of 2, then the compiler could
replace the multiply by a shift, which is a bit faster.

> Also, keep in mind that
> I/O is pretty much _the_ most expensive thing you can do in C/C++ (the only
> things that could even come close are RTTI (typeid, dynamic_cast, etc)

What does RTTI stand for?

> , and
> memory allocation). Mostly because memory busses are so slow compared to CPUs.

Memory accesses are probably a bit slow as well then???

So presumably, for a for loop, going through and indexing an array, the storage
or
retrieval of elements in the array will also be slow --- compared with
calculating
the index anyway.  To what extent is this true?

> 2 thoughts:
>
>   *) Read the sayings from a file? Of course if you're just using sayings as
> an example maybe this isn't so applicable.

Yes, it is just an example.  I do read stuff from a file.  However at times it is

convenient to be able to hardwire something, and it would be nice to be
able to hardwire a vector of stuff (and other things too) in a straightforward
manner --- without having to do lots of "push_back"s.

>   *) I think the only way to do that is pre-declare an array somewhere.
> Actually, this could be nicer anyway. For example:
>
> sayings.cpp:
>
> string sayings[] = {
>  "saying1",
>  "saying2",
>  "END OF SAYINGS" // this is dirty, but potentially better than hard coding
>                   // the size.
> };

Yes this is okay for my example, but I am
wanting something which will work more
generally.  I tried a variant on your approach
based on a class:

class wiseSayingsTy: public vector<string> {
public:
  wiseSayingsTy(): vector<string>() {}
  wiseSayingsTy(uint N, char const* initList[]): vector<string>() {
    for (int i=0; i<N; i++)
      push_back(initList[i]);
  }
};

Then I hoped I could write:

  wiseSayingsTy wiseSayings(4, {"eat more chocolate", "smell the roses",
    "laugh a little", "keep it simple"});

But it wouldn't compile, complaining that:

  tst_main.cpp:114: parse error before `{'

It sounds like the array initializer only works in certain
circumstances???

Cheers,

Mark.





More information about the tuxCPProgramming mailing list