[英]Order of Vector elements for C++
The following piece of c++ code gives 下面的c ++代码给出了
int main()
{
vector <int> myvect(3,0);
vector <int> :: iterator it;
it = myvect.begin();
myvect.insert(it,200);
myvect.insert(it+5,400); //Not sure what 5 makes the difference here
cout << myvect[0] << endl << myvect[1];
}
Output : 输出:
200
400
And the same code with minor changes gives 并且相同的代码有微小的变化
int main()
{
vector <int> myvect(3,0);
vector <int> :: iterator it;
it = myvect.begin();
myvect.insert(it,200);
myvect.insert(it+4,400); //Not sure what 4 makes the difference here
cout << myvect[0] << endl << myvect[1];
}
Output: 输出:
400
200
Can someone tell me why adding 4 or 5 to the iterator changes the order of elements? 有人能告诉我为什么在迭代器中添加4或5会改变元素的顺序吗?
Thanks 谢谢
Your program has Undefined Behavior . 您的程序具有未定义的行为 。
You are creating a vector of 3 elements (all initialized to 0), and you are inserting elements at position v.begin() + 5
, which is beyond the end of the vector. 您正在创建一个包含3个元素的向量(全部初始化为0),并且您将在位置
v.begin() + 5
处插入元素,这超出了向量的末尾。
Moreover, you are using an iterator ( it)
after inserting an element before the position it
points to. 而且, 在
it
指向的位置之前插入元素之后,您正在使用迭代器( it)
。 According to Paragraph 23.3.6.5/1 of the C++11 Standard: 根据C ++ 11标准的第23.3.6.5/1段:
[...] If no reallocation happens, all the iterators and references before the insertion point remain valid.
[...]如果没有重新分配, 插入点之前的所有迭代器和引用仍然有效。 [...]
[...]
Therefore, iterator it
itself is not guaranteed to be valid after the statement myvect.insert(it, 200)
, and using it in the next instruction ( myvect.insert(it + 4, 400)
) is again Undefined Behavior. 因此,迭代器
it
本身不能保证会后声明有效myvect.insert(it, 200)
并在接下来的说明书,使用它( myvect.insert(it + 4, 400)
又是未定义的行为。
You cannot expect anything of a program with Undefined Behavior. 您不能指望任何具有未定义行为的程序。 It may crash, give you bizarre results, or (in the worst case) behave just as you would expect.
它可能会崩溃,给你奇怪的结果,或者(在最坏的情况下)表现得像你期望的那样。
The member function vector::insert(const_iterator, const value_type&)
requires a valid iterator that refers to the vector but it+4
and it+5
are not valid iterators. 成员函数
vector::insert(const_iterator, const value_type&)
需要一个引用向量的有效迭代器,但it+4
而it+5
不是有效的迭代器。
Before the first insertion, it+3
is a valid (non-dereferencable) iterator, pointing just past-the-end of the vector sequence, but it+4
is invalid. 在第一次插入之前,
it+3
是一个有效的(不可解除引用的)迭代器,指向矢量序列的末尾,但it+4
是无效的。 After the insertion it
might get invalidated, in which case no expression using it
is valid, certainly not it+5
because the sequence only has four elements at that point. 插入后
it
可能会失效,在这种情况下,使用it
表达式无效,当然不是it+5
因为序列在该点只有四个元素。
The code would be valid if changed like so: 如果改变,代码将是有效的:
it = myvect.begin();
myvect.insert(it,200);
it = myvect.begin(); // make it valid again
myvect.insert(it+4,400);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.