Vector elements

Which is better to use for accessing a certan value with in a vector?


myvector.at(i) = i;

or

myvector[i] = i;

As far as I know, they do both the same thing. Is there any reason to use one over the other?
use of [] is simpler, otherwise I don't see any other reason
I found out why,

[] is faster and less demanding while .at is safer since it throws out_of_range expection.
Nicked from:
http://www.cplusplus.com/reference/stl/vector/at/

The difference between this member function and member operator function operator[] is that vector::at signals if the requested position is out of range by throwing an out_of_range exception.


So if you want to protect access using exceptions, use at()

Andy
Hi, your solutions is very good for two forms, use of operator [] is very simpler!!!

Example

for ( int i =0; i < myvector.size(); i++)
cout<< myvector[i] <<endl;

redgards
alex
Topic archived. No new replies allowed.