What if size argument for std::vector::resize is equal to the current size?

限于喜欢 提交于 2021-01-28 01:59:36

问题


Reading the manual about vector::resize http://www.cplusplus.com/reference/vector/vector/resize/

It only says what happens if the size is greater or smaller, but does not say what happens if it's equal. Is it guaranteed that on equal size it will not reallocate the array and invalidate the iterators?

I wanted to avoid one branch and handle only 2 cases (>= or <) instead of 3 (< or > or ==), but if resizing to same size is undefined, then i will have to check that case too.


回答1:


This is probably just an error in the linked reference. The standard says following:

void resize(size_type sz);

Effects: If sz < size(), erases the last size() - sz elements from the sequence. Otherwise, appends sz - size() default-inserted elements to the sequence.

Since sz - size() is 0 in your case, it doesn't do anything.




回答2:


From [vector]

Effects: If sz < size(), erases the last size() - sz elements from the sequence. Otherwise, appends sz - size() default-inserted elements to the sequence.

In the case that size() == sz it inserts 0 elements into the sequence, which is the same as doing nothing.




回答3:


Now, probably most implementations are sufficiently intelligent about the case where nothing needs to be done and will literally do nothing.

But I am asking myself, you are intending to call resize, why are you holding iterators anyway? Basically, you should never hold iterators for any longer time, especially when containers may get resized. Just write your algorithms in ways that don't need to hold iterators over the resize point.

I am guessing wildly here, but maybe you are not using the right container and more context about what you are trying to achieve may result in a more useful answer.




回答4:


It seems like you're asking if iterators will be invalidated when resize(size()) is called. The answer is no, iterators will not be invalidated. Probably very little will happen at all, but certainly not iterator invalidation, because that only happens when the storage has to be reallocated, which would never happen if the resize is a no-op.




回答5:


std::vector<> implementation:

void resize(size_type __new_size)
{
    if (__new_size > size())
        _M_default_append(__new_size - size());
    else if (__new_size < size())
        _M_erase_at_end(this->_M_impl._M_start + __new_size);
}

So, as expected: It does nothing.

Edit:
Taken from my RHEL server, g++ and C++ library package version 5.3.



来源:https://stackoverflow.com/questions/53447386/what-if-size-argument-for-stdvectorresize-is-equal-to-the-current-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!