在 C++ 中访问向量的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8221702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:12:19  来源:igfitidea点击:

Accessing elements of a vector in C++?

c++vector

提问by fdh

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

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

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.

我四处搜索,但找不到类似的问题。如果这样的问题已经存在,请转发给我,我会删除这个问题。

回答by Alok Save

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

std::vector::at()通过抛出out_of_bounds异常,防止您访问数组元素越界,这与[]访问超出向量边界时不会警告或抛出异常的运算符不同。

std::vectoris/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::vectorit 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::vectorover c-style arrays and hence they also provided std::Vector::at()method which provides it.

std::vector是/被认为是 c99 中可变长度数组 (VLA) 的 c++ 替换/构造。为了让 c 风格的数组容易被替换std::vector,向量需要提供与数组类似的接口,因此向量提供[]了访问其元素的运算符。同时,C++ 标准委员会可能也觉得需要为std::vectorC 风格的数组提供额外的安全性,因此他们也提供std::Vector::at()了提供它的方法。

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::vectorprovides you both the options to be safe or to be faster at expense of managing the safety yourself.

自然地,at()方法在取消引用之前检查向量的大小,这对于通过 访问元素会产生一点开销(在大多数用例中可能可以忽略不计)[],因此std::vector为您提供了安全或以管理为代价更快的选项自己的安全。

回答by Jason B

As others have mentioned, at()performs bounds checking and []does not. Two reasons I can think of to prefer []are:

正如其他人所提到的,at()执行边界检查[]但不执行。我能想到的两个原因[]是:

  1. Cleaner syntax
  2. Performance. When looping through the elements of a vector, it is often overkill and very costly to perform bounds checking on every iteration.
  1. 更简洁的语法
  2. 表现。当循环遍历向量的元素时,在每次迭代中执行边界检查通常是过度的并且成本非常高。

回答by Frank

at()

at()

Pros:

优点:

  • safe because exception is thrown if array out of bounds
  • 安全,因为如果数组越界就会抛出异常

Cons:

缺点:

  • slow access
  • more characters to type
  • 访问缓慢
  • 要输入更多字符

operator[]

operator[]

Pros:

优点:

  • fast access because of missing bounds checks
  • less characters to type
  • 'intuitive' array element access
  • 由于缺少边界检查而快速访问
  • 要输入的字符更少
  • “直观”的数组元素访问

Cons:

缺点:

  • unsafe because of missing bounds checks
  • 由于缺少边界检查而不安全

回答by CStreel

Personal Choice

个人选择

The reason some people use the Subscript Operator is that they intuitive as a vector is similar to an array accessing the items this way is simply put as 'syntactic sugar' meaning it makes it look nicer.

有些人使用下标运算符的原因是他们直观,因为向量类似于访问项目的数组,这种方式只是简单地作为“语法糖”,这意味着它看起来更好。

Some people prefer the [], and others prefer the .at(), it's personal choice.

有些人喜欢[],有些人喜欢.at(),这是个人选择。

The Technical Choice

技术选择

Assuming you're talking about access only, the Function .at()does bounds checking and it throws an exception when you attempt to access an item beyond the bounds. The function is 'safer', but if you are handling bounds checking yourself, feel free to use the subscript operator!

假设您只讨论访问,该函数.at()会进行边界检查,当您尝试访问超出边界的项目时,它会抛出异常。该函数“更安全”,但如果您自己处理边界检查,请随意使用下标运算符!

So really it's up to you to choose which style of accessor you use!

所以真的由你来选择你使用哪种风格的配饰!

回答by Bill

You're correct .at() is safer because it will check array bounds. operator[] skips the check, and is undefined if you make an illegal access.

你是对的 .at() 更安全,因为它会检查数组边界。operator[] 跳过检查,如果您进行非法访问则未定义。

Traditional array access in C/C++ has never had array bounds checking, and back in the 90's before Java was introduced many felt that it would add unacceptable overhead. I believe that, in general, this is not true today, and it wasn't as true as many believed at the time either. I'm sure that there are cases where it matters, but in general you're better off starting safe and switching if you find a compelling need to do so.

C/C++ 中的传统数组访问从未进行过数组边界检查,在 Java 引入之前的 90 年代,许多人认为这会增加不可接受的开销。我相信,总的来说,今天的情况并非如此,也不像当时许多人所认为的那样真实。我确信在某些情况下它很重要,但一般来说,如果您发现迫切需要这样做,最好先安全启动并切换。

回答by Seva Alekseyev

The subscript operator has less typing involved, which makes the code more clear. Also, refactoring to/from a C array comes naturally.

下标操作符涉及的类型较少,这使得代码更加清晰。此外,从 C 数组重构到/从 C 数组重构是很自然的。

回答by Prabhu

I use STLPort 5.2.Seems at()does a range check.

我使用STLPort 5.2.似乎at()进行范围检查。

reference at(size_type __n) { _M_range_check(__n); return (*this)[__n]; }

参考 at(size_type __n) { _M_range_check(__n); return (*this)[__n]; }