vector::resize | public member function |
void resize ( size_type sz, T c = T() ); |
Change size
Resizes the vector to contain sz elements.
If sz is smaller than the current vector size, the content is reduced to its first sz elements, the rest being dropped.
If sz is greater than the current vector size, the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements. This may cause a reallocation.
Notice that this function changes the actual content of the vector by inserting or erasing elements from the vector; It does not only change its storage capacity. To direct a change only in storage capacity, use vector::reserve instead.
Parameters
- sz
- New vector size, expressed in elements.
Member type size_type is an unsigned integral type. - c
- Object whose content is copied to the added elements in case that sz is greater than the current vector size.
If not specified, the default constructor is used.
T is the first template parameter (the type of the elements stored in the vector).
Return Value
noneIf a reallocation happens, it is performed using Allocator::allocate(), which may throw exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Example
// resizing vector #include <iostream> #include <vector> using namespace std; int main () { vector<int> myvector; unsigned int i; // set some initial content: for (i=1;i<10;i++) myvector.push_back(i); myvector.resize(5); myvector.resize(8,100); myvector.resize(12); cout << "myvector contains:"; for (i=0;i<myvector.size();i++) cout << " " << myvector[i]; cout << endl; return 0; } |
The code sets a sequence of 9 numbers as an initial content for myvector. It then uses resize first to trim the vector to a size of 5, then to extend its size to 8 with values of 100 for its new elements, and finally it extends its size to 12 with their default values (for int elements this is zero). Output:
myvector contains: 1 2 3 4 5 100 100 100 0 0 0 0 |
Complexity
Linear on the number of elements inserted/erased (constructions/destructions).See also
vector::size | Return size (public member function) |
vector::clear | Clear content (public member function) |
vector::max_size | Return maximum size (public member function) |