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

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

问题描述

我知道 at() 由于其边界检查而比 [] 慢,这也在类似的问题中讨论,例如 C++ Vector at/[] operator speed::std::vector::at() 与 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::vectorv(10); 并且我决定在我有索引 i 的情况下使用 at() 而不是 [] 来访问它的元素 并且我不确定它是否在向量范围内,它迫使我用 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;

所以我的问题是:
使用 vector::atvector::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[] ?

推荐答案

我想说的是 vector::at() 抛出的异常并不是真的要被周围的对象捕获代码.它们主要用于捕获代码中的错误.如果您需要在运行时进行边界检查,因为例如索引来自用户输入,您确实最好使用 if 语句.所以总而言之,设计你的代码时要保证 vector::at() 永远不会抛出异常,所以如果它抛出异常,并且你的程序中止,那就是一个错误的迹象.(就像一个 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 与 vector::operator[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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