附加std :: vector到自身,未定义的行为? [英] Appending std::vector to itself, undefined behavior?

查看:152
本文介绍了附加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的表11 ISO规范),作为序列要求的一部分,序列容器中的操作 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 c $ c> a 。

i, j are not iterators into 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到自身,未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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