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[] ?