[Effective-cpp] Item 1: Uses and Abuses of vector

Ric Parkin ric.parkin at ntlworld.com
Tue Oct 26 08:23:53 EDT 2004


David Sykes <davidsykes234 at yahoo.com>
> I wonder if the use of v[n] is a candidate for premature optimisation

It depends - if you know that your indexes cannot be out of range, then it's avoiding unneccesary pressimisation :-)

eg, consider implementing a simple find index into vector function

template < typename T >
int find_index( const std::vector<T>& v, const T& t )
{
  for ( int i = 0, e = v.size(); i != e; ++i )
    if ( t == v[i] )
      return i;
  return std::vector<T>::npos;
}

Here I can prove that i is always in range, so why pay for the needless overhead of using at? 

(Note that several other micro choices in that code snippet are there not because it's premature optimisation, but because of the absence of any good reason to not use the usually just as fast and more general idioms.)



As for the question that came up about when would you use at? Well, it's where you want to access an element by index, you have to validate the index, and you want an invalid index signalled by throwing an out_of_range exception.

This last point tends to be missed as far I have seen: if you want some other way of signalling it, eg a magic value, or a domain layer specific exception, then it's often easier and clearer to test by hand, and then call [] if everything's okay.

And sometimes, I'll just define an interface's contract that passing in out of range indexes results in undefined behaviour. Then I've a choice of whether to catch errors and how to report them.

So I don't tend to use at very often at all.

Ric


-----------------------------------------
Email provided by http://www.ntlhome.com/





More information about the Effective-cpp mailing list