我应该在代码中使用std :: vector :: at()吗? [英] Should I use std::vector::at() in my code

查看:162
本文介绍了我应该在代码中使用std :: vector :: at()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天注意到,std::vector::at()的访问速度明显比方括号[]的访问速度慢.根据文档,.at()是更安全的,因为它不会让我访问超出数组范围的值.但是,即使我使用at()访问超出范围的值,显然我仍然会出现错误,因此无论如何我都需要避免这种情况.

I noticed today that std::vector::at() is significantly slower than accessing values with square brackets []. According to the doc .at() is safer because it won't let me access values beyond the bounds of the array. However, even if I access out of bound values with at(), I'll obviously still have an error, so that's something I need to avoid no matter what.

那么,为什么有人会使用at()代替[]呢?

So is there any good reason why anyone would use at() instead of []?

推荐答案

如果您有理由相信索引不在您的控件中,或者如果控件流程特别复杂并且您正在跟踪错误,那么您可能会希望在调试阶段使用at(),但切勿在循环内或任何您知道索引安全的情况下使用.

If you have reason to believe that the index is not in your control, or if the control flow is particularly complicated and you're tracing bugs, then you might want to use at() during the debug phase, but never inside loops or any situation where you know that the index is safe.

即使在其他情况下,您也应该预先验证索引(例如,如果是用户输入),或者如果您只是从复杂算法中获取值,请使用assert并修复存在的错误. 或者,如果您正在编写一个非常复杂的算法,并且不确定所有索引是否始终有效,则可以在该算法内部使用at()并将调用放入尝试阻止-但即使在这种情况下,最好还是冒犯并与断言一起使用.[/]

Even in other situations you should either prevalidate the index (e.g. if it's user input), or if you are just getting the value from a complicated algorithm, use assert and fix the bug if there is one. Or perhaps if you are writing a very complicated algorithm and you aren't sure that all your indices are always valid, you could use at() inside that algorithm and put the call into a try block -- but even here it is preferable to be offensive and use with assertions.[/]

就我个人而言,我看不到at()能够生存到发行代码中的任何充分理由.您可能会想到一些示例,这些示例中您想使用异常处理作为指导控制流的便捷方法,但是任何此类用例都是非常实际的情况.

Personally, I can't see any good reasons for at() to survive into release code. You could possibly contrive some examples where you want to use exception handling as a convenient way to direct your control flow, but any such use case would be very situational.

这篇关于我应该在代码中使用std :: vector :: at()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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