Appending std::vector to itself, undefined behavior?(将 std::vector 附加到自身,未定义的行为?)
问题描述
这个问题让我不确定向自身附加一个向量.所以问题是:以下代码行符合我的预期,但是否符合标准?
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:
i、j 不是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 附加到自身,未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 std::vector 附加到自身,未定义的行为?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
