If I have a vector,
std::vector<int> MyVector;
And want to access the n'th element of that vector, I can do so in many different ways:
int x = MyVector[n];
or
int x = MyVector.at(n);
or even using iterators that I am not familiar with.
I am sure there are also many more ways in which a object in a vector can be accessed. What I am asking is, what are the pro's and cons of each and therefore which method would be the "best" if any.
Also, is there any saftey benifets of any of these? If not why would anyone use .at(x) over [x]?
tl;dr answer:
what are the pro's and cons of each[?]
[]
doesn't do bounds-checking, i.e. it is unsafer and slightly faster.
at
does bounds-checking, i.e. it is safer and slightly slower.
Good rule of thumb: If performance is not a problem, use at
, otherwise, use []
.
If you want to access nth element because std::vector is zero indexed it should be as follows:
int x = MyVector[n-1];
or
int x = MyVector.at(n-1);
If you use std::vector:at()
it will check the boundary condition and throw out_of_range
exception if you try to access an element beyond the range. But in all other mechanisms to access vector element you will get undefined behavior if you try to use out of range index.
Another standard template library mechanism is std::vector::iterator
to access the elements of vector. std::vector<>
provides random access iterator. Iterators will be useful whenever you use standard algorithms because they expects iterators
as their parameters most of the time.
It really depends on WHY you want to access the n'th element (e.g. to change it, to compare it with something, to insert something before or after it) and the patterns of values of n. You have not described any of those concerns, so the only real answer is "it depends". There is no "best" for all circumstances - if there was, then the vector specification would probably only provide that means of access.
Every method of access had different advantages and disadvantages, depending on the pattern of access and reason for it.
For example, different techniques are suited to accessing one element of a vector repeatedly versus sequentially accessing every element versus accessing some set of elements in random order versus accessing every second value, versus n always being a valid index versus n sometimes being an invalid index (so a check of the value is needed is needed).
std::vector simulates dynamically allocated arrays. So the most common way of the access to elements of a vector is using the subscript operator.
Iterators are not really useful with a vector, as you can have random access with [] or at, both work in the same way, the only difference between them (as I read on the reference), is that at throws an out-of-range exception if you are out of bounds, while [] not (I guess this could also make at a bit slower)