正在自学数据结构,遇到一个问题(如图)始终难以理解:_size=lo
为更新规模,或者说丢弃尾部的操作,为什么不是hi=_size
,因为元素移位后,有效的数据序列应该是n-hi+lo
位置之前的元素构成的,也就是vi[hi]
之后的元素都应该丢弃,所以hi=_size
不是很合理吗。
希望大神可以帮忙解决,谢谢!
伊谢尔伦2017-04-17 13:36:29
Because the elements between [hi,_size] are used to cover the elements in the [lo, _size+lo-hi] interval.
hi increases to _size, and the corresponding lo will increase to _size+lo- hi,
that is, _size+lo-hi is the position of the last element, that is, the new _size value
The code uses lo to mark the position of the last element, so the final size is _size=lo.
怪我咯2017-04-17 13:36:29
In this function, lo
and hi
are both value-passed parameters, that is, these two values are destroyed after the function is completed.
is a member of vector
. It uses _size
to determine the number of elements saved. _size
So what needs to be modified here is
, not _size
. hi
黄舟2017-04-17 13:36:29
hi=_size
Unreasonable
hi
is the right endpoint of the interval to be deleted at the beginning, and after while
ends, it represents the right endpoint of the remaining elements; before _size is updated, it represents the right endpoint of the element before it is deleted, while
After the end, the unupdated _size is meaningless. What the hell is assigning hi to _size
lo
and hi
are local variables (parameters), and their scope is within the function. They are destroyed after the function is executed. It is meaningless to update hi
.
represents the size of the vector _size, which is the value returned by calling v.size(), so _size