为什么使用“vector.at(x)”好于“矢量[x]”。在C ++? [英] Why is using "vector.at(x)" better than "vector[x]" in C++?

查看:120
本文介绍了为什么使用“vector.at(x)”好于“矢量[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);

现在我可以做这两件事了。

Now I can do both things

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() throws 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.

没人说在() 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()当我想要它抛出异常,如果无效的索引,所以我可以做替代工作在 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(),但它会混合正常代码与替代代码使用 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)”好于“矢量[x]”。在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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