baci
baci

Reputation: 2588

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 ?

Upvotes: 2

Views: 830

Answers (1)

David G
David G

Reputation: 96845

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.

Upvotes: 5

Related Questions