list::resize | public member function |
void resize ( size_type sz, T c = T() ); |
Change size
Resizes the container to contain sz elements.
If sz is smaller than the current container size, the content is reduced to its first sz elements, the rest being dropped.
If sz is greater than the current container size, the content is expanded by inserting at the end as many copies of c as needed to reach a size of sz elements.
Notice that this function changes the actual content of the container by inserting or erasing elements from it.
Parameters
- sz
- New container size, expressed in number of 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 container size.
If not specified, the default constructor is used.
T is the first template parameter (the type of the elements stored in the container).
Return Value
noneIn case of growth, the storage for the new elements is allocated using Allocator::allocate(), which may throw exceptions on failure (for the default allocator, bad_alloc is thrown if the allocation request does not succeed).
Example
// resizing list #include <iostream> #include <list> using namespace std; int main () { list<int> mylist; unsigned int i; // set some initial content: for (i=1;i<10;i++) mylist.push_back(i); mylist.resize(5); mylist.resize(8,100); mylist.resize(12); cout << "mylist contains:"; for (list<int>::iterator it=mylist.begin();it!=mylist.end();++it) cout << " " << *it; cout << endl; return 0; } |
The code sets a sequence of 9 numbers as an initial content for mylist. It then uses resize first to set the container size to 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:
mylist contains: 1 2 3 4 5 100 100 100 0 0 0 0 |
Complexity
If the container grows, linear in the number number of elements inserted (constructor).If the container shrinks, linear on the number of elements erased (destructions)plus up to linear on the new size (iterator advance).
See also
list::size | Return size (public member function) |
list::clear | Clear content (public member function) |
list::erase | Erase elements (public member function) |
list::max_size | Return maximum size (public member function) |