我可以从空 std 容器的 front() 得到什么?

发布于 2024-07-16 15:03:12 字数 124 浏览 6 评论 0原文

如果 front() 返回一个引用并且容器是空的,我会得到什么,一个未定义的引用? 这是否意味着我需要在每个 front() 之前检查 empty()

If front() returns a reference and the container is empty what do I get, an undefined reference? Does it mean I need to check empty() before each front()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

罪#恶を代价 2024-07-23 15:03:12

你会得到未定义的行为 - 在调用 front() 之前,你需要使用 empty() (检查容器是否为空)检查容器是否包含某些内容。

You get undefined behaviour - you need to check that the container contains something using empty() (which checks if the container is empty) before calling front().

↙厌世 2024-07-23 15:03:12

你会得到未定义的行为。

要进行范围检查,请使用 at(0)。 如果失败,您将收到 out_of_range 异常。

You get undefined behaviour.

To get range checking use at(0). If this fails you get a out_of_range exception.

初见终念 2024-07-23 15:03:12

是的,你可以像 Graham 提到的那样使用“at”,而不是使用 front。

但是,at(0) 仅适用于某些容器 - 向量、双端队列,而不适用于其他容器 - 列表、队列、堆栈。 在这些情况下,您必须依靠“空”支票的安全性。

Yes, you can use 'at' like Graham mentioned instead of using front.

But, at(0) is only available for some containers - vectors, deque and not for others - list, queue, stack. In these cases you've to fall back on the safety of the 'empty' check.

狂之美人 2024-07-23 15:03:12

在此实例上调用 front() 之前,您始终必须确保容器不为空。
调用empty()作为安全防护是很好的。

当然,根据您的程序设计,始终拥有一个非空容器可能是一个不变的语句,允许您在每次调用 front() 时阻止并保存对empty() 的调用。 (或者至少在代码的某些部分?)

但如上所述,如果您想避免程序中出现未定义的行为,请使其成为强不变量。

You've always have to be sure your container is not empty before calling front() on this instance.
Calling empty() as a safe guard is good.

Of course, depending on your programm design, always having a non-empty container could be an invariant statement allowing you to prevent and save the call to empty() each time you call front(). (or at least in some part of your code?)

But as stated above, if you want to avoid undefinied behavior in your program, make it a strong invariant.

皓月长歌 2024-07-23 15:03:12

未定义的行为

Undefined Behaviour

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文