vector :: at vs. vector :: operator [] [英] vector::at vs. vector::operator[]

查看:330
本文介绍了vector :: at vs. vector :: operator []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 at() [] 慢,因为它的边界检查在类似问题(例如 C ++向量at / []运算符速度)或 :: std :: vector :: at()vs operator []<惊人的结果! 5到10倍更慢/更快!。我只是不明白 at()方法是否有用。

I know that at() is slower than [] because of its boundary checking, which is also discussed in similar questions like C++ Vector at/[] operator speed or ::std::vector::at() vs operator[] << surprising results!! 5 to 10 times slower/faster!. I just don't understand what the at() method is good for.

如果我有一个简单的向量像这样: std :: vector< int> v(10); 并且我决定通过使用在()而不是 [] 在我有一个索引 i 的情况下,我不知道如果它的向量边界,它强迫我包装它与try-catch ::

If I have a simple vector like this one: std::vector<int> v(10); and I decide to access its elements by using at() instead of [] in situation when I have a index i and I'm not sure if its in vectors bounds, it forces me to wrap it with try-catch block:

try
{
    v.at(i) = 2;
}
catch (std::out_of_range& oor)
{
    ...
}

虽然我可以通过使用 size()并检查我的索引自己,这对我来说更容易和更方便:

although I'm able to do the get the same behaviour by using size() and checking the index on my own, which seems easier and much convenient for me:

if (i < v.size())
    v[i] = 2;

所以我的问题是:

a href =http://www.cplusplus.com/reference/stl/vector/at/> vector :: at vector :: operator []

我应该何时使用 vector::at 而不是 vector :: size + vector :: operator []

So my question is:
What are advantages of using vector::at over vector::operator[] ?
When should I use vector::at rather than vector::size + vector::operator[] ?

推荐答案

code> throws并不是真正意图被立即包围的代码捕获。它们主要用于捕获代码中的错误。如果您需要在运行时进行边界检查,因为例如索引来自用户输入,你最好使用 if 语句。所以总的来说,设计你的代码,意图 vector :: at()永远不会抛出异常,所以如果它,并且你的程序中止,它是一个符号的bug。 (就像 assert()

I'd say the exceptions that vector::at() throws aren't really intended to be caught by the immediately surrounding code. They are mainly useful for catching bugs in your code. If you need to bounds-check at runtime because e.g. the index comes from user input, you're indeed best off with an if statement. So in summary, design your code with the intention that vector::at() will never throw an exception, so that if it does, and your program aborts, it's a sign of a bug. (just like an assert())

这篇关于vector :: at vs. vector :: operator []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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