访问C ++中的向量元素? [英] Accessing elements of a vector in C++?

查看:113
本文介绍了访问C ++中的向量元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现人们使用数组括号[]和法向量函数.at()。为什么有两个单独的方法?两者的优点和缺点是什么?我知道.at()是更安全的,但有没有任何情况下,.at()不能使用?如果.at()总是更安全,为什么要使用数组括号[]。



我搜索过,但找不到类似的问题。

解决方案

如果这样的问题已经存在请转发给我,我将删除此问题。 std :: vector :: at()通过抛出 out_of_bounds 异常不像 [] 运算符,当访问超出向量边界时不会警告或抛出异常。



std :: vector 是/被视为可变长度数组(VLA)的c ++替换/ c99。为了使c-style数组可以很容易地被 std :: vector 替换,需要向量提供一个类似于数组的接口,因此向量提供 [] 运算符。同时,C ++标准委员会也许还需要为c-style数组提供 std :: vector 的额外安全性,因此他们还提供了



自然地, at()

code>方法在解引用之前检查向量的大小,并且在 [] 访问元素时会有一些开销(在大多数使用情况下可能是微不足道的) ,所以 std :: vector 为您提供了安全的选项或更快的选项,自己管理安全。


I often found people use the array brackets [] and a normal vector function .at (). Why are there two separate methods? What are the benefits and disadvantages of both? I know that .at () is safer, but are there any situations where .at () cannot be used? And if .at () is always safer, why ever use array brackets [].

I searched around but couldn't find a similar question. If a questions like this already exists please forward me to it and I will delete this question.

解决方案

std::vector::at() guards you against accessing array elements out of bounds by throwing an out_of_bounds exception unlike the [] operator which does not warn or throw exceptions when accessing beyond the vector bounds.

std::vector is/was considered as an c++ replacement/construct for Variable Length Arrays(VLA) in c99. In order for c-style arrays to be easily replacable by std::vector it was needed that vectors provide a similar interface as that of an array, hence vector provides [] operator for accessing its elements. At the same time, C++ standards committee perhaps also felt the need for providing additional safety for std::vector over c-style arrays and hence they also provided std::Vector::at() method which provides it.

Naturally, at() method checks for the size of the vector before dereferencing it and that will be a little overhead (perhaps negligible in most use cases) over accessing elements by [], So std::vector provides you both the options to be safe or to be faster at expense of managing the safety yourself.

这篇关于访问C ++中的向量元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆