Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the design rationale behind the resize method of std::vector?

Tags:

c++

stdvector

Many methods within the template class vector take a const reference to value_type objects, for instance:

void push_back (const value_type& val);

while resize takes its value_type parameter by value:

void resize (size_type n, value_type val = value_type());

As a non-expert C++ programmer I can only think of disadvantages with this choice (for instance if size_of(value_type) is big enough stack overflow may occur). What I would like to ask to people with more insight on the language is thus:

What is the design rationale behind this choice?

like image 392
Massimiliano Avatar asked May 15 '13 16:05

Massimiliano


People also ask

What does resize in vector do C++?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.

How does std::vector resize work?

std::vector::resizeResizes the container to contain count elements. If the current size is greater than count , the container is reduced to its first count elements as if by repeatedly calling pop_back() . If the current size is less than count , additional elements are appended and initialized with copies of value .

Why we use resize in C++?

vector::resize() The function alters the container's content in actual by inserting or deleting the elements from it. It happens so, If the given value of n is less than the size at present then extra elements are demolished.

Does resize change capacity?

Calling resize() with a smaller size has no effect on the capacity of a vector . It will not free memory.


1 Answers

void resize( size_type count, T value = T() );

This function has been removed from C++11.

C++11 has two overloads of resize():

void resize( size_type count );
void resize( size_type count, const value_type& value);

which is pretty much straightforward to understand. The first one uses default constructed objects of type value_type to fill vector when resizing, the second takes a value from which it makes copies when resizing.

like image 132
Nawaz Avatar answered Nov 14 '22 15:11

Nawaz