Deque constructors

Syntax:

    #include <deque>
    deque();
    deque( const deque& c );
    deque( size_type num, const TYPE& val = TYPE() );
    deque( input_iterator start, input_iterator end );

The default deque constructor takes no arguments, creates a new instance of that deque.

The second constructor is a default copy constructor that can be used to create a new deque that is a copy of the given deque c.

The third constructor creates a deque 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 deque consisting of five copies of the integer 42:

   deque<int> dq( 5, 42 );

The last constructor creates a deque that is initialized to contain the elements between start and end. For example:

   // create a deque of random integers
   cout << "original deque: ";
   deque<int> dq;
   for( int i = 0; i < 10; i++ ) {
     int num = static_cast<int>(rand() % 10);
     cout << num << " ";
     dq.push_back( num );
   }
   cout << endl;
 
   // find the first element of dq that is even
   deque<int>::iterator iter1 = dq.begin();
   while( iter1 != dq.end() && *iter1 % 2 != 0 ) ++iter1;
 
   // find the last element of dq that is even
   deque<int>::iterator iter2 = dq.end();
   do {
     --iter2;
   } while( iter2 != dq.begin() && *iter2 % 2 != 0 );
 
   cout << "first even number: " << *iter1 << ", last even number: " << *iter2 << endl;
 
   cout << "new deque: ";
   deque<int> dq2( iter1, iter2 );
   for( size_t i = 0; i < dq2.size(); i++ ) {
     cout << dq2[i] << " ";
   }
   cout << endl;

When run, this code displays the following output:

   original deque: 1 9 7 9 2 7 2 1 9 8
   first even number: 2, last even number: 8
   new deque: 2 7 2 1 9

In addition to containers and iterators, the STL also works with pointers and arrays. For example, the following code creates a deque using data from an array and pointer arithmetic:

  // create a deque from an array of integers
  const int ARR_SIZE = 4;
  int vals[ARR_SIZE] = { 13, 26, 5, 979 };
  deque<int> dq( vals, vals + sizeof(vals)/sizeof(int) );
 
  cout << "dq is: ";
  for( size_t i = 0; i < dq.size(); ++i ) cout << dq[i] << " ";
  cout << '\n';

All of these constructors run in linear time except the first, which runs in constant time.