简体   繁体   中英

C++ STL accessing vector element

What is the difference between vector.at(i) and 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. Also I read about at checks for vector size (bounds) and returns out of bounds error, whereas [] does not.

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 ? Why is it in the STL ?

operator [] for std::vector will return a reference to the area of memory whether it was allocated for the vector or not. Accessing an unallocated area of memory is Undefined Behavior, whereas at will throw an exception before any of that occurs. As @JoachimPileborg said in the comments the unspecified behavior of operator [] includes throwing exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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