Youda008
Youda008

Reputation: 1949

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

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.

Upvotes: 3

Views: 3757

Answers (5)

Rene
Rene

Reputation: 2474

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.

Upvotes: 2

Caleth
Caleth

Reputation: 62616

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.

Upvotes: 4

Zereges
Zereges

Reputation: 5209

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.

Upvotes: 5

rioki
rioki

Reputation: 6118

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.

Upvotes: 3

John Zwinck
John Zwinck

Reputation: 249123

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.

Upvotes: 1

Related Questions