No, this is not the right way to do this. For ::std::vector or ::std::string it works fine, but the problem is that if you ever use anything else, it won’t work that well. Also, this is not idiomatic.
And to answer your other question ... The size function is probably inline. This means that it most likely extracts the value from the internal elements ::std::string or ::std::vector . The compiler optimizes this and only retrieves it once in most cases.
But here is the idiomatic way:
for (::std::vector<Foo>::iterator i = theContainer.begin(); i != theContainer.end(); ++i) { Foo &cur_element = *i; // Do stuff }
++i very important. Again, for ::std:vector or ::std::string , where the iterator is basically a pointer, this is not so important. But for more complex data structures, this is so. i++ must make a copy and create a temporary one, because the old value must be adhered to. ++i does not have such a problem. Get in the habit of always using ++i unless you have a good reason not to.
Finally, theContainer.end() will also be generally optimized from existence. But you can make things be a little better by doing this:
const ::std::vector<Foo>::iterator theEnd = theContainer.end(); for (::std::vector<Foo>::iterator i = theContainer.begin(); i != theEnd; ++i) { Foo &cur_element = *i; // Do stuff }
Of course, C ++ 0x greatly simplifies all this thanks to the new syntax for for loops:
for (Foo &i: theContainer) {
They will work with standard arrays of fixed sizes, as well as with any type that defines begin and end to return iterative things.
Omnifarious
source share