If I want to get to a value in vector I can use two options : use the [] operator. Or I might use the function .at example for using :
vector<int> ivec;
ivec.push_back(1);
Now I can do both things
int x1 = ivec[0];
int x2 = ivec.at(0); // or
I heard using at is a better option because when I use that option I can throw this one in an exception.
Can somebody please explain this?
The difference between
c[i]andc.at(i)is thatat()throwsstd::out_of_rangeexception ififalls outside the range of the vector, whileoperator[]simply invokes undefined behavior, which means anything can happen.Nobody says
at()is better thanoperator[]. It just depends on circumstances. Asat()performs range check, it may not be desirable always, especially when your code itself makes sure that the index can never fall outside the range. In such cases,operator[]is better.Consider the following loop:
In such a loop,
operator[]is always a better choice in comparison toat()member function.I would prefer
at()when I want it throw exception in case of invalid index, so that I could do the alternative work in thecatch{ ...}block. Exceptions help you separate the normal code from the exceptional/alternative code as:Here you could check
iyourself, to make sure that it is a valid index, and then calloperator[]instead ofat(), but it would mix the normal code with the alternative code usingif-elseblock which makes it difficult to read the normal flow of code. If you see above,try-catchimproves the code readability, as it really separates the normal code from the alternative code, resulting in a neat and clean code.