I know that at()
is slower than []
because of its boundary checking, which is also discussed in similar questions like C++ Vector at/[] operator speed or ::std::vector::at() vs operator[] << surprising results!! 5 to 10 times slower/faster!. I just don't understand what the at()
method is good for.
If I have a simple vector like this one: std::vector<int> v(10);
and I decide to access its elements by using at()
instead of []
in situation when I have a index i
and I'm not sure if its in vectors bounds, it forces me to wrap it with try-catch block:
try
{
v.at(i) = 2;
}
catch (std::out_of_range& oor)
{
...
}
although I'm able to do the get the same behaviour by using size()
and checking the index on my own, which seems easier and much convenient for me:
if (i < v.size())
v[i] = 2;
So my question is:
What are advantages of using vector::at over vector::operator[] ?
When should I use vector::at rather than vector::size + vector::operator[] ?
if (i < v.size()) v[i] = 2;
, there's a possible code path that doesn't assign2
to any element ofv
at all. If that's the correct behavior, great. But often there's nothing sensible that this function can do wheni >= v.size()
. So there's no particular reason why it shouldn't use an exception to indicate an unexpected situation. Many functions just useoperator[]
without a check against the size, document thati
must be in range, and blame the resulting UB on the caller. – Steve Jessopat
is safer. For example, given anobj
vector with 100 elements. Theobj.at(143) = 69;
explodes right away. Whereas,obj[143] = 69;
will silently creep in without your notice. – eigenfield