Deitel & Associates, Inc. Logo

Back to www.deitel.com
digg.png delicious.png blinkit.png furl.png
C++ How to Program, 5/e

ISBN:
0-13-185757-6
© 2005
pages: 1500
Buy the Book!
Amazon logo
InformIT logo

 

23.2.3 deque Sequence Container (continued)

Figure 23.18 demonstrates features of class deque. Remember that many of the functions presented in Fig. 23.14, Fig. 23.15 and Fig. 23.17 also can be used with class deque. Header file <deque> must be included to use class deque.

Line 13 instantiates a deque that can store double values. Lines 17–19 use functions push_front and push_back to insert elements at the beginning and end of the deque. Remember that push_back is available for all sequence containers, but push_front is available only for class list and class deque.

 1  // Fig. 23.18: Fig23_18.cpp
 2  // Standard Library class deque test program.
 3  #include <iostream>
 4  using std::cout;
 5  using std::endl;
 6
 7  #include <deque> // deque class-template definition
 8  #include <algorithm> // copy algorithm
 9  #include <iterator> // ostream_iterator
10
11  int main()
12  {
13     std::deque< double > values; // create deque of doubles
14     std::ostream_iterator< double > output( cout, " " );
15
16     // insert elements in values
17     values.push_front( 2.2 );
18     values.push_front( 3.5 );
19     values.push_back( 1.1 );
20
21     cout << "values contains: ";
22
23     // use subscript operator to obtain elements of values
24     for ( unsigned int i = 0; i < values.size(); i++ )
25        cout << values[ i ] << ' ';
26
27     values.pop_front(); // remove first element
28     cout << "\nAfter pop_front, values contains: ";
29     std::copy( values.begin(), values.end(), output );
30
31     // use subscript operator to modify element at location 1
32     values[ 1 ] = 5.4;
33     cout << "\nAfter values[ 1 ] = 5.4, values contains: ";
34     std::copy( values.begin(), values.end(), output );
35     cout << endl;
36     return 0;
37  } // end main
 values contains: 3.5 2.2 1.1
 After pop_front, values contains: 2.2 1.1
 After values[ 1 ] = 5.4, values contains: 2.2 5.4

Fig. 23.18 Standard Library deque class template.

The for statement at lines 24–25 uses the subscript operator to retrieve the value in each element of the deque for output. Note that the condition uses function size to ensure that we do not attempt to access an element outside the bounds of the deque.

Line 27 uses function pop_front to demonstrate removing the first element of the deque. Remember that pop_front is available only for class list and class deque (not for class vector).

Line 32 uses the subscript operator to create an lvalue. This enables values to be assigned directly to any element of the deque.

Page 1 | 2

Tutorial Index