访问矢量对象的最佳方法 [英] Best way to access vector objects
问题描述
如果我有矢量,
std::vector<int> MyVector;
并且想要访问该向量的第n个元素,我可以通过许多不同的方式进行访问:
And want to access the n'th element of that vector, I can do so in many different ways:
int x = MyVector[n];
或
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.
还有,其中任何一个有什么安全的好处?如果不是,为什么有人会在[x]上使用.at(x)?
Also, is there any saftey benifets of any of these? If not why would anyone use .at(x) over [x]?
推荐答案
tl; dr 答案:
各自的优点和缺点是什么[?]
what are the pro's and cons of each[?]
-
[]
不进行边界检查,即不安全和稍快. -
at
进行边界检查,即更安全,并且稍慢. []
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.
好的经验法则:如果性能不是问题,请使用at
,否则请使用[]
.
Good rule of thumb: If performance is not a problem, use at
, otherwise, use []
.
这篇关于访问矢量对象的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!