[LC++]STL Iterators and integers

Jack Lloyd lloyd at acm.jhu.edu
Sat Aug 4 00:51:05 UTC 2001


>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. 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), and
memory allocation). Mostly because memory busses are so slow compared to CPUs.

>I'm not sure which one would be more efficient.  Possibly they are the same
>thing???

Probably pretty close. I recommend the first because it's clearer.

>Unfortunately, it doesn't work.  Is there any way of
>doing something like this?

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. But I've found it's better to read
stuff from a file rather than hard code it so you don't have to recompile if
you change one little thing. Because it's a big pain, you be suprised at how
often you'll want to add/remove/change something.

  *) 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.
};

some_other_file.cpp:

extern string sayings[];

// initalize the vector and use it

An alternate implementation of sayings.cpp could be:

static const int SAYINGS_COUNT = 2;

int how_many_sayings() { return SAYINGS_COUNT; }

strings sayings[] = {
 "saying1",
 "saying2"
};

That way there is no end of array marker, your other code just calls
how_many_sayings() to know how many elements are in the sayings[] array.

With this method, stuff is still hard-coded, but you only have to recompile
the sayings file if you change something (one last thought: you could replace
string with const char* in sayings.cpp, which would compile a lot faster and
work exactly the same, since you can initalize a string with a const char*).

Jack




More information about the tuxCPProgramming mailing list