将 std::vector 附加到自身,未定义的行为?

Appending std::vector to itself, undefined behavior?(将 std::vector 附加到自身,未定义的行为?)
本文介绍了将 std::vector 附加到自身,未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

这个问题让我不确定向自身附加一个向量.所以问题是:以下代码行符合我的预期,但是否符合标准?

This question made me uncertain about appending a vector to itself. So the question is: Following lines of code do what I expect, but is it standard conform?

vec.reserve(vec.size() * 2):
vec.insert(vec.end(), vec.begin(), vec.end());

以下(没有reserve())仍然有效,是否符合标准?

Following (without reserve()) still works, is it even standard conform?

vec.insert(vec.end(), vec.begin(), vec.end());

还是取决于实现?

推荐答案

根据 C++03 ISO 规范(§23.1.1,表 67)(以及@AndyProwl 在 §23.2.3 中提到的, C++11 ISO 规范的表 11),作为序列要求的一部分,序列容器中的操作 a.insert(p, i, j) 具有以下前提条件:

According to the C++03 ISO spec (§23.1.1, Table 67) (and as @AndyProwl has mentioned, in §23.2.3, table 11 of the C++11 ISO spec), as part of sequence requirements, the operation a.insert(p, i, j) in a sequence container has this precondition:

ij 不是a 的迭代器.

换句话说,允许序列容器安全地假设,如果您执行范围插入操作,则该范围将不会从原始容器上的迭代器中定义.

In other words, sequence containers are allowed to safely assume that if you do a range insertion operation, that range will not be defined from iterators over that original container.

因此,如果您尝试将容器的元素插入到自身中,您就是在调用标准库函数并破坏了前提条件.这会导致未定义的行为,这意味着如果库实现者是好人,它可能在某些平台上工作,但它可能会在没有任何理由的情况下发生可怕的灾难性失败.

As a result, if you try to insert a container's elements into itself, you are calling a standard library function and breaking a precondition. This results in undefined behavior, meaning that it might work on some platforms if the library implementers are nice people, but it could terribly and catastrophically fail with no justification.

希望这有帮助!

这篇关于将 std::vector 附加到自身,未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)