简体   繁体   English

C ++ STL访问向量元素

[英]C++ STL accessing vector element

What is the difference between vector.at(i) and vector[i] ? vector.at(i)vector[i]什么区别?

vector<int> myVector(6);
myVector.at(5) = 5;

OR 要么

myVector[5] = 5;

I know both yield the same result, but somehow the operator [] is faster. 我知道两者都会产生相同的结果,但是以某种方式,operator []会更快。 Also I read about at checks for vector size (bounds) and returns out of bounds error, whereas [] does not. 此外,我阅读有关at检查矢量的大小(边界),并返回出界错误 ,而[]没有。

However I saw that if try to assign: 但是我看到,如果尝试分配:

myVector[8] = 1;

I get a similar out of range error in debug mode. 在调试模式下,我收到类似的超出范围错误。

Then what is the meaning of at ? 那么at的含义是什么? Why is it in the STL ? 为什么在STL中?

operator [] for std::vector will return a reference to the area of memory whether it was allocated for the vector or not. std::vector operator []将返回对内存区域的引用,无论是否为向量分配了该引用。 Accessing an unallocated area of memory is Undefined Behavior, whereas at will throw an exception before any of that occurs. 访问未分配的内存区域是未定义行为,而at会在发生任何异常之前引发异常。 As @JoachimPileborg said in the comments the unspecified behavior of operator [] includes throwing exceptions. 就像@JoachimPileborg在评论中说的那样, operator []的未指定行为包括抛出异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM