为什么使用“vector.at(x)"?比“vector[x]"更好在 C++ 中? [英] Why is using "vector.at(x)" better than "vector[x]" in C++?

查看:21
本文介绍了为什么使用“vector.at(x)"?比“vector[x]"更好在 C++ 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想获得向量中的值,我可以使用两个选项:使用 [] 运算符.或者我可以使用函数 .at 来使用:

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);

现在我可以做这两件事

int x1 = ivec[0];
int x2 = ivec.at(0); // or

我听说使用 at 是一个更好的选择,因为当我使用该选项时,我可以将其抛出异常.

I heard using at is a better option because when I use that option I can throw this one in an exception.

有人可以解释一下吗?

推荐答案

c[i]c.at(i) 的区别在于 at() 抛出 std::out_of_range 异常如果 i 落在向量范围之外,而 operator[] 只是调用未定义的行为,这意味着任何事情都可能发生.

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.

没有人说 at()operator[] 更好.这只是取决于情况.由于 at() 执行范围检查,它可能并不总是可取的,尤其是当您的代码本身确保索引永远不会超出范围时.在这种情况下,operator[] 更好.

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.

考虑以下循环:

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

在这样的循环中,operator[] 总是比 at() 成员函数更好的选择.

In such a loop, operator[] is always a better choice in comparison to at() member function.

我更喜欢 at() 当我希望它在索引无效的情况下抛出异常时,这样我就可以在 catch{ ...} 阻止.异常帮助您将正常代码与异常/替代代码分开:

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
}

这里你可以自己检查i,确保它是一个有效的索引,然后调用operator[]而不是at()code>,但它会使用 if-else 块将普通代码与替代代码混合在一起,这使得普通代码流难以阅读.如果您在上面看到,try-catch 提高了代码的可读性,因为它真正地将普通代码与替代代码分开,从而产生整洁干净的代码.

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.

这篇关于为什么使用“vector.at(x)"?比“vector[x]"更好在 C++ 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆