重叠vector :: insert的行为 [英] The behavior of overlapped vector::insert

查看:164
本文介绍了重叠vector :: insert的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++标准声明传递给 std :: vector :: insert 的那对迭代器不能与原始序列重叠?



编辑:详细说明,我很确定标准不需要标准库来处理这样的情况:

  std :: vector< int> v(10); 
std :: vector< int> :: iterator first = v.begin()+ 5;
std :: vector< int> :: iterator last = v.begin()+ 8;
v.insert(v.begin()+ 2,first,last);

但是,我在标准中找不到任何东西,会禁止范围 [first,last) [v.begin(),v.end()) $ b

解决方案

23.1.1 / 4序列要求有:



em> a.insert(p,i,j)



返回类型: void



前提条件: i,j不是迭代器

因此 i j



这是有意义的,因为在插入操作期间,向量可能需要调整自己的大小,因此,现有元素可以首先被复制到新的存储器位置(通过使当前迭代器无效)。


Where does the C++ standard declare that the pair of iterators passed to std::vector::insert must not overlap the original sequence?

Edit: To elaborate, I'm pretty sure that the standard does not require the standard library to handle situations like this:

std::vector<int> v(10);
std::vector<int>::iterator first = v.begin() + 5;
std::vector<int>::iterator last = v.begin() + 8;
v.insert(v.begin() + 2, first, last);

However, I was unable to find anything in the standard, that would prohibit the ranges [first, last) and [v.begin(), v.end()) to overlap.

解决方案

23.1.1/4 Sequence requirements has:

expression: a.insert(p,i,j)

return type: void

precondition: i,j are not iterators into a. inserts copies of elements in[i,j) before p.

So i and j cannot be iterators into your vector.

It makes sense, as during the insert operation, the vector may need to resize itself, and so the existing elements may first be copied to a new memory location (there by invalidating the current iterators).

这篇关于重叠vector :: insert的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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