List constructors
Syntax:
#include <list> list(); list( const list& c ); list( size_type num, const TYPE& val = TYPE() ); list( input_iterator start, input_iterator end ); ~list();
The default list constructor takes no arguments, creates a new instance of that list.
The second constructor is a default copy constructor that can be used to create a new list that is a copy of the given list c.
The third constructor creates a list with space for num objects. If val is specified, each of those objects will be given that value. For example, the following code creates a list consisting of five copies of the integer 42:
list <int> l1( 5, 42 );
The last constructor creates a list that is initialized to contain the elements between start and end. For example:
// create a vector of random integers cout << "original list: "; list<int> l; for( int i = 0; i < 20; i++ ) { int num = (int) rand() % 10; cout << num << " "; l.push_back( num ); } cout << endl; // delete 5 & 7 list<int>::iterator iter1 = l.begin(); while( iter1 != l.end() ) { list<int>::iterator thisone = iter1; iter1++; if ( *thisone == 5 || *thisone == 7 ) { cout << "erase " << *thisone << endl; l.erase( thisone ); } } // find the first element of l that is even list<int>::iterator iter2 = l.begin(); while( iter2 != l.end() && *iter2 % 2 != 0 ) { iter2++; } // find the last element of l that is even list<int>::iterator iter3 = l.end(); do { iter3--; } while( iter3 != l.begin() && *iter3 % 2 != 0 ); cout << "first even number: " << *iter2 << ", last even number: " << *iter3 << endl; cout << "new list: "; list<int> l2( iter2, iter3 ); list<int>::iterator iter4 = l2.begin(); while( iter4 != l2.end() ) { cout << *iter4 << " "; iter4++; } cout << endl;
When run, this code displays the following output:
original list: 7 9 3 8 0 2 4 8 3 9 0 5 2 2 7 3 7 9 0 2 erase 7 erase 5 erase 7 erase 7 first even number: 8, last even number: 2 new list: 8 0 2 4 8 3 9 0 2 2 3 9 0
All of these constructors run in linear time except the first, which runs in constant time.
The default destructor calls the destructor for each object in the list with linear complexity.