vector::at vs. vector::operator[](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::vector
并且我决定在我有索引 i 的情况下使用
并且我不确定它是否在向量范围内,它迫使我用 try-catch 块包装它:at()
而不是 []
来访问它的元素
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::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[] ?
推荐答案
我想说的是 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[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:vector::at 与 vector::operator[]
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01