问题描述
我知道 at()
由于其边界检查而比 []
慢,这也在类似的问题中讨论,例如 C++ Vector at/[] operator speed 或 ::std::vector::at() 与 operator[] .我只是不明白 at()
方法有什么用.
try
{
v.at(i) = 2;
}
catch (std::out_of_range& oor)
{
...
}
虽然我可以通过使用 size()
并自己检查索引来获得相同的行为,这对我来说似乎更容易和方便:
if (i < v.size())
v[i] = 2;
所以我的问题是:
使用 vector::at 比 ?
我什么时候应该使用 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[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!