Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

exception - Why is using "vector.at(x)" better than "vector[x]" in C++?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The difference between c[i] and c.at(i) is that at() throws std::out_of_range exception if i falls outside the range of the vector, while operator[] simply invokes undefined behavior, which means anything can happen.

Nobody says at() is better than operator[]. It just depends on circumstances. As at() 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:

for(size_t i = 0 ; i < v.size(); ++i)
{
   //Should I use v[i] or v.at(i)?
}

In such a loop, operator[] is always a better choice in comparison to at() 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 the catch{ ...} block. Exceptions help you separate the normal code from the exceptional/alternative code as:

try
{
   size_t i = get_index(); //I'm not sure if it returns a valid index!

   T item = v.at(i); //let it throw exception if i falls outside range

   //normal flow of code
   //...
}
catch(std::out_of_range const & e)
{
   //alternative code
}

Here you could check i yourself, to make sure that it is a valid index, and then call operator[] instead of at(), but it would mix the normal code with the alternative code using if-else block which makes it difficult to read the normal flow of code. If you see above, try-catch improves the code readability, as it really separates the normal code from the alternative code, resulting in a neat and clean code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...