Vector - use [] or .at() to initialise

I have a vector of bytes. I want to initialise this vecotor and don't know to use the [] operator or the .at() function.
The documentation states that the only difference is that the .at() operator throws an exception.

Which is the best one to use and why?

I will be doing the following:
1
2
3
4
5
for (i=0; i< length; i++)
{
	myvector[i] = mybyte; //use this
	myvector.at( i ) = mybyte;//or this
}
Looking at the the MSVC STL headers - they are the same code.
The at() function checks that the index if within the bounds - if it is not it will throw an exception.

The [] operator does not perform the bounds check. If the index is out of bounds then the behaviour of the program will be undefined.

I would stick with .at() initially. There is a performance trade-off, but it might be insignificant. When it comes to optimisation you will be able to tell if there is significant gain using the [] operator, and if that is the case it shouldn't take too long to switch them over.

If you are new to programming then I'd go with at().

Good luck!

Nick.
Last edited on
at checks whether you pass a valid index, [] does not
This is from the GCC implementation of at:
1
2
3
4
5
6
reference
      at(size_type __n)
      {
	_M_range_check(__n);
	return (*this)[__n]; 
      }
My mistake in looking up the code.
The at function performs an additional check, which can hurt performance in some cases.
As long as it is assured that the index is within the vector bounds, you should use operator[].

However, in this case, you should use iterators anyway:
for (auto it=myvector.begin();it!=myvector.end();++it)*it=mybyte;

Which is just the manual version of fill:
fill(myvector.begin(),myvector.end(),mybyte);

Or if this is supposed to be done at/right after creation:
vector<int> myvector(length,mybyte);

Edit: oops, too late. Forgot to hit "submit".
Last edited on
closed account (z05DSL3A)
The standard says that at() has bounds checking but the subscript operator this is not specified. This means that any particular implementation may or may not do bounds checking on subscript operations.

I believe that VC (2005,2008) used to do bounds checking on both debug and release builds by default and VC 2010 it is default in debug but not in release builds. This is configurable via defines IIRC.
Topic archived. No new replies allowed.