Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 83

1

2
2
Standard Template
Library (STL)

 2006 Pearson Education, Inc. All rights reserved.


2

23.1 Introduction to the Standard Template Library (STL)


23.1.1 Introduction to Containers
23.1.2 Introduction to Iterators
23.1.3 Introduction to Algorithms
23.2 Sequence Containers
23.2.1 vector Sequence Container
23.2.2 list Sequence Container
23.2.3 deque Sequence Container
23.3 Associative Containers
23.3.1 multiset Associative Container
23.3.2 set Associative Container
23.3.3 multimap Associative Container
23.3.4 map Associative Container
23.4 Container Adapters
23.4.1 stack Adapter
23.4.2 queue Adapter
23.4.3 priority_queue Adapter

 2006 Pearson Education, Inc. All rights reserved.


3
23.1 Introduction to the Standard
Template Library (STL)
• Standard Template Library (STL)
– Defines powerful, template-based, reusable components
and algorithms to process them
• Implement many common data structures
– Developed by Alexander Stepanov and Meng Lee
– Conceived and designed for performance and flexibility
– Three key components
• Containers
• Iterators
• Algorithms

 2006 Pearson Education, Inc. All rights reserved.


4
23.1 Introduction to the Standard
Template Library (STL) (Cont.)
• STL containers
– Three container categories
• First-class containers
• Adapters
• Near containers
– Each container has associated member functions
• Some member functions are defined in all STL containers

 2006 Pearson Education, Inc. All rights reserved.


5
23.1 Introduction to the Standard
Template Library (STL) (Cont.)
• STL iterators
– Used to manipulate STL-container elements
• Have properties similar to those of pointers
– Standard pointers can be used as iterators
• So standard arrays can be manipulated as STL containers

 2006 Pearson Education, Inc. All rights reserved.


6
23.1 Introduction to the Standard
Template Library (STL) (Cont.)
• STL algorithms
– Perform common data manipulations such as searching,
sorting and comparing
– Mostly use iterators to access container elements
• Each algorithm has minimum iterator requirements
– Can be used on any container whose supported iterator
type satisfies those requirements

 2006 Pearson Education, Inc. All rights reserved.


7

23.1.1 Introduction to Containers


• STL containers
– Three major categories
• Sequence containers
– Represent linear data structures
• Associative containers
– Nonlinear containers
– Store key/value pairs
• Container adapters
– Implemented as constrained sequence containers
– “Near-containers”
• Pointer-based arrays, strings, bitsets and valarrays

 2006 Pearson Education, Inc. All rights reserved.


8

Standard Library
Description
container class

Sequence containers
Vector rapid insertions and deletions at back
direct access to any element
deque rapid insertions and deletions at front or back
direct access to any element
list doubly linked list, rapid insertion and deletion anywhere
Associative containers
set rapid lookup, no duplicates allowed
multiset rapid lookup, duplicates allowed
map one-to-one mapping, no duplicates allowed, rapid key-based
lookup
multimap one-to-many mapping, duplicates allowed, rapid key-based
lookup
Container adapters
stack last-in, first-out (LIFO)
queue first-in, first-out (FIFO)
priority_queue highest-priority element is always the first element out

Fig. 23.1 | Standard Library container classes.

 2006 Pearson Education, Inc. All rights reserved.


9

23.1.1 Introduction to Containers (Cont.)

• STL containers (Cont.)


– Common functions
• All STL containers provide similar functionality
• Many generic operations apply to all containers
• Others apply of subsets of similar containers
– Header files
• STL containers are found in various header files
• STL containers are all in namespace std

 2006 Pearson Education, Inc. All rights reserved.


10

Common member
functions for all STL Description
containers
default constructor A constructor to provide a default initialization of the
container. Normally, each container has several
constructors that provide different initialization methods for
the container.
empty Returns true if there are no elements in the container;
otherwise, returns false.
Size Returns the number of elements currently in the container.
operator= Assigns one container to another.
operator< Returns true if the first container is less than the second
container; otherwise, returns false.
operator<= Returns true if the first container is less than or equal to
the second container; otherwise, returns false.
operator> Returns true if the first container is greater than the
second container; otherwise, returns false.
operator>= Returns true if the first container is greater than or equal
to the second container; otherwise, returns false.
operator== Returns true if the first container is equal to the second
container; otherwise, returns false.
operator!= Returns true if the first container is not equal to the second
container; otherwise, returns false.
swap Swaps the elements of two containers.

Fig. 23.2 | STL container common functions. (Part 1 of 2)

 2006 Pearson Education, Inc. All rights reserved.


11

Common member
functions for all STL Description
containers
Functions found only in first-class containers
max_size Returns the maximum number of elements for a container.
begin The two versions of this function return either an
iterator or a const_iterator that refers to the first
element of the container.
end The two versions of this function return either an
iterator or a const_iterator that refers to the next
position after the end of the container.
rbegin The two versions of this function return either a
reverse_iterator or a const_reverse_iterator
that refers to the last element of the container.
rend The two versions of this function return either a
reverse_iterator or a const_reverse_iterator
that refers to the next position after the last element of the
reversed container.
erase Erases one or more elements from the container.
clear Erases all elements from the container.

Fig. 23.2 | STL container common functions. (Part 2 of 2)

 2006 Pearson Education, Inc. All rights reserved.


12

Standard Library container header files

<vector>
<list>
<deque>
<queue> Contains both queue and priority_queue.
<stack>
<map> Contains both map and multimap.
<set> Contains both set and multiset.
<bitset>

Fig. 23.3 | Standard Library container header files.

 2006 Pearson Education, Inc. All rights reserved.


13

typedef Description

value_type The type of element stored in the container.


Reference A reference to the type of element stored in the container.
const_reference A constant reference to the type of element stored in the
container. Such a reference can be used only for reading
elements in the container and for performing const
operations.
pointer A pointer to the type of element stored in the container.
iterator An iterator that points to the type of element stored in the
container.
const_iterator A constant iterator that points to the type of element
stored in the container and can be used only to read
elements.

Fig. 23.4 | typedefs found in first-class containers. (part 1 of 2)

 2006 Pearson Education, Inc. All rights reserved.


14

typedef Description

reverse_iterator A reverse iterator that points to the type of element


stored in the container. This type of iterator is for
iterating through a container in reverse.
const_reverse_iterator A constant reverse iterator that points to the type of
element stored in the container and can be used only to
read elements. This type of iterator is for iterating
through a container in reverse.
difference_type The type of the result of subtracting two iterators that
refer to the same container (operator - is not defined
for iterators of lists and associative containers).
size_type The type used to count items in a container and index
through a sequence container (cannot index through a
list).

Fig. 23.4 | typedefs found in first-class containers. (part 2 of 2)

 2006 Pearson Education, Inc. All rights reserved.


15

23.1.1 Introduction to Containers (Cont.)

• STL containers (Cont.)


– Type requirements for STL container elements
• Elements must be copied to be inserted in a container
– Element’s type must provide copy constructor and
assignment operator
• Compiler will provide default memberwise copy and
default memberwise assignment, which may or may
not be appropriate
• Elements might need to be compared
– Element’s type should provide equality operator and
less-than operator

 2006 Pearson Education, Inc. All rights reserved.


16

23.1.2 Introduction to Iterators


• STL iterators
– Have many features in common with pointers
• Used to point to elements of first-class containers
• Dereferencing operator (*) accesses current element
• ++ operator moves iterator to next element of the container
– Hold state information for their particular containers
– First-class container member functions
• Member function begin
– Returns iterator pointing to first element
• Member function end
– Returns iterator pointing just past last element

 2006 Pearson Education, Inc. All rights reserved.


17

23.1.2 Introduction to Iterators (Cont.)

• STL iterators (Cont.)


– iterator versus const_iterator
• const_iterators cannot modify container elements
– Iterators are used with sequences (also called ranges)
• Sequences can be in containers
• Sequences can be input or output sequences
– istream_iterator
• An iterator for an input sequence
– ostream_iterator
• An iterator for an output sequence

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.5: Fig23_05.cpp
18
2
3
// Demonstrating input and output with iterators.
#include <iostream>
Outline
4 using std::cout;
5 using std::cin;
6 using std::endl;
Fig23_05.cpp
7
8 #include <iterator> // ostream_iterator and istream_iterator
9
(1 of 2)
Create an istream_iterator
10 int main()
11 {
capable of extracting int values
12 cout << "Enter two integers: "; from standard input cin
13
14 // create istream_iterator for reading int values from cin Dereference istream_iterator
15 std::istream_iterator< int > inputInt( cin );
inputInt to read an int from cin
16
17 int number1 = *inputInt; // read int from standard input
Position istream_iterator inputInt
18 ++inputInt; // move iterator to next input value
19 int number2 = *inputInt; // read int from standard input
to the next value in the input stream
20
21 // create ostream_iterator for writing int values to cout Create an ostream_iterator
22 std::ostream_iterator< int > outputInt( cout ); capable of inserting int values
23
into standard output cout
24 cout << "The sum is: ";
25 *outputInt = number1 + number2; // output result to cout
26 cout << endl;
27 return 0; Dereference outputInt and use it as
28 } // end main
an lvalue to output an integer to cout

 2006 Pearson Education,


Inc. All rights reserved.
19
Enter two integers: 12 25
Outline
The sum is: 37

Fig23_05.cpp

(2 of 2)

 2006 Pearson Education,


Inc. All rights reserved.
20

23.1.2 Introduction to Iterators (Cont.)

• STL iterators (Cont.)


– Iterator categories
• Input – can move forward one position, can read elements
• Output – can move forward one position, can write elements
• Forward – can move forward one position, can read and
write elements
• Bidirectional – can move forward or backward one position,
can read and write elements
• Random access – can move forward or backward any
number of positions, can read and write elements
– Each category supports all functionality of categories
above it
– Iterator category determines what algorithms can be used

 2006 Pearson Education, Inc. All rights reserved.


21

Category Description

input Used to read an element from a container. An input iterator can move
only in the forward direction (i.e., from the beginning of the container
to the end) one element at a time. Input iterators support only one-pass
algorithms—the same input iterator cannot be used to pass through a
sequence twice.
output Used to write an element to a container. An output iterator can move
only in the forward direction one element at a time. Output iterators
support only one-pass algorithms—the same output iterator cannot be
used to pass through a sequence twice.
forward Combines the capabilities of input and output iterators and retains
their position in the container (as state information).
bidirectional Combines the capabilities of a forward iterator with the ability to move
in the backward direction (i.e., from the end of the container toward
the beginning). Bidirectional iterators support multipass algorithms.
random access Combines the capabilities of a bidirectional iterator with the ability to
directly access any element of the container, i.e., to jump forward or
backward by an arbitrary number of elements.

Fig. 23.6 | Iterator categories.

 2006 Pearson Education, Inc. All rights reserved.


22

Fig. 23.7 | Iterator category hierarchy.

 2006 Pearson Education, Inc. All rights reserved.


23

Container Type of iterator supported

Sequence containers (first class)


Vector random access
Deque random access
List bidirectional
Associative containers (first class)
set bidirectional
multiset bidirectional
map bidirectional
multimap bidirectional
Container adapters
stack no iterators supported
queue no iterators supported
priority_queue no iterators supported

Fig. 23.8 | Iterator types supported by each Standard Library container.

 2006 Pearson Education, Inc. All rights reserved.


24

Predefined typedefs for iterator types Direction of ++ Capability

iterator forward read/write


const_iterator forward read
reverse_iterator backward read/write
const_reverse_iterator backward read

Fig. 23.9 | Iterator typedefs.

 2006 Pearson Education, Inc. All rights reserved.


25

Iterator operation Description

All iterators
++p Preincrement an iterator.
p++ Postincrement an iterator.
Input iterators
*p Dereference an iterator.
p = p1 Assign one iterator to another.
p == p1 Compare iterators for equality.
p != p1 Compare iterators for inequality.
Output iterators
*p Dereference an iterator.
P = p1 Assign one iterator to another.
Forward iterators Forward iterators provide all the functionality of both input
iterators and output iterators.
Bidirectional iterators
--p Predecrement an iterator.
p-- Postdecrement an iterator.

Fig. 23.10 | Iterator operations for each type of iterator. (Part 1 of 2 )

 2006 Pearson Education, Inc. All rights reserved.


26

Iterator operation Description

Random-access iterators
p += i Increment the iterator p by i positions.
p -= i Decrement the iterator p by i positions.
p + i Expression value is an iterator positioned at p incremented by
i positions.
p - i Expression value is an iterator positioned at p decremented
by i positions.
p[ i ] Return a reference to the element offset from p by i positions
p < p1 Return true if iterator p is less than iterator p1 (i.e., iterator
p is before iterator p1 in the container); otherwise, return
false.
p <= p1 Return true if iterator p is less than or equal to iterator p1
(i.e., iterator p is before iterator p1 or at the same location as
iterator p1 in the container); otherwise, return false.
p > p1 Return true if iterator p is greater than iterator p1 (i.e.,
iterator p is after iterator p1 in the container); otherwise,
return false.
p >= p1 Return true if iterator p is greater than or equal to iterator
p1 (i.e., iterator p is after iterator p1 or at the same location
as iterator p1 in the container); otherwise, return false.

Fig. 23.10 | Iterator operations for each type of iterator. (Part 2 of 2 )

 2006 Pearson Education, Inc. All rights reserved.


27

23.1.3 Introduction to Algorithms


• STL algorithms
– Can be used generically across many containers
• Inserting, deleting, searching, sorting, etc.
– Operate on container elements only indirectly through
iterators
• Many operate on sequences defined by pairs of iterators
– First iterator points to first element of sequence
– Second iterator points one past last element of sequence
• Often return iterators to indicate results
• Can be used on containers that support the necessary
iterator, or containers that support more powerful iterators

 2006 Pearson Education, Inc. All rights reserved.


28

Mutating-sequence algorithms

copy remove reverse_copy


copy_backward remove_copy rotate
fill remove_copy_if rotate_copy
fill_n remove_if stable_partition
generate replace swap
generate_n replace_copy swap_ranges
iter_swap replace_copy_if transform
partition replace_if unique
random_shuffle reverse unique_copy

Fig. 23.11 | Mutating-sequence algorithms.

 2006 Pearson Education, Inc. All rights reserved.


29

Nonmodifying sequence algorithms

adjacent_find find find_if


count find_each mismatch
count_if find_end search
equal find_first_of search_n

Fig. 23.12 | Nonmutating sequence algorithms.

 2006 Pearson Education, Inc. All rights reserved.


30

Numerical algorithms from header file <numeric>

accumulate partial_sum
inner_product adjacent_difference

Fig. 23.13 | Numerical algorithms from header file <numeric>.

 2006 Pearson Education, Inc. All rights reserved.


31

23.2 Sequence Containers


• STL sequence containers
– Three sequence containers
• vector – a more robust type of array
• list – implements a linked-list data structure
• deque – based on arrays
– Common operations of sequence containers
• front returns reference to first element
• back returns reference to last element
• push_back inserts new element to the end
• pop_back removes last element

 2006 Pearson Education, Inc. All rights reserved.


32

23.2.1 vector Sequence Container


• Class template vector
– A data structure with contiguous memory locations
• Efficient, direct access to any element via subscript operator
– Or member function at, which provides range-checking
– Commonly used when data must be sorted and easily
accessible via subscript
– When additional memory is needed
• Allocates larger contiguous memory, copies elements and
deallocates old memory
– Supports random-access iterators
• All STL algorithms can operate on vectors
– Requires header file <vector>

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.14: Fig23_14.cpp
33
2
3
// Demonstrating Standard Library vector class template.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
Fig23_14.cpp
7 #include <vector> // vector class-template definition
8 using std::vector;
9
(1 of 3)
10 // prototype for function template printVector
11 template < typename T > void printVector( const vector< T > &integers2 );
12
13 int main()
14 { Define a vector called integers
15 const int SIZE = 6; // define array size that stores int values
16 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 }; // initialize array
17 vector< int > integers; // create vector of ints
18 Return the number of
19 cout << "The initial size of integers is: " << integers.size() elements currently
20 << "\nThe initial capacity of integers is: " << integers.capacity();
stored in the container
21
22 // function push_back is in every sequence collection
23 integers.push_back( 2 );
24 integers.push_back( 3 );
Return the numberof elements that can be stored in the
25 integers.push_back( 4 ); vector before it needs to dynamically resize itself
Add elements to the end of the vector
26 to accommodate more elements
27 cout << "\nThe size of integers is: " << integers.size()
28 << "\nThe capacity of integers is: " << integers.capacity();
29 cout << "\n\nOutput array using pointer notation: ";

 2006 Pearson Education,


Inc. All rights reserved.
30
34
31
32
// display array using pointer notation
for ( int *ptr = array; ptr != array + SIZE; ptr++ )
Outline
33 cout << *ptr << ' ';
34
35 cout << "\nOutput vector using iterator notation: ";
Fig23_14.cpp
36 printVector( integers );
37 cout << "\nReversed contents of vector integers: ";
38
(2 of 3)
39 // two const reverse iterators
40 vector< int >::const_reverse_iterator reverseIterator;
41 vector< int >::const_reverse_iterator tempIterator = integers.rend();
42
43 // display vector in reverse order using reverse_iterator
44 for ( reverseIterator = integers.rbegin();
45 reverseIterator!= tempIterator; ++reverseIterator )
46 cout << *reverseIterator << ' ';
47
48 cout << endl;
49 return 0;
reverseIterator iterates from the position returned
50 } // end main
by rbegin until just before the position returned by
rend to output the vector elements in reverse order

 2006 Pearson Education,


Inc. All rights reserved.
51
35
52 // function template for outputting vector elements
Outline
53 template < typename T > void printVector( const vector< T > &integers2 )
54 {
55 typename vector< T >::const_iterator constIterator; // const_iterator
56 Fig23_14.cpp
57 // display vector elements using const_iterator
Tell the compiler that vector< T >
58 for ( constIterator = integers2.begin(); (3 of 3)
::const_iterator is expected
59 constIterator != integers2.end(); ++constIterator )
60 cout << *constIterator << ' ';
to be a type in every specialization
61 } // end function printVector
constIterator iterates through the
The
The
initial size of integers is: 0
initial capacity of integers is: 0
vector and outputs its contents
The size of integers is: 3
The capacity of integers is: 4
The vector’s capacity increases to
Output array using pointer notation: 1 2 3 4 5 6 accommodate the growing size
Output vector using iterator notation: 2 3 4
Reversed contents of vector integers: 4 3 2

 2006 Pearson Education,


Inc. All rights reserved.
36
23.2.1 vector Sequence Container
(Cont.)
• Class template vector (Cont.)
– Member function insert
• Inserts a value at location specified by iterator argument
• Overloaded versions
– Insert multiple copies of a value
– Insert a range of values from another container
– Member function erase
• Remove the element at location specified by iterator
argument
• Or remove a range of elements specified by two iterator
arguments

 2006 Pearson Education, Inc. All rights reserved.


37
23.2.1 vector Sequence Container
(Cont.)
• STL algorithm function copy
– Copies each element in the specified container into the
other specified container
• First and second arguments specify source container
– Must be at least input iterators
• Third argument specifies beginning of destination container
– Must be at least output iterator
– Requires header file <algorithm>

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.15: Fig23_15.cpp
38
2
3
// Testing Standard Library vector class template
// element-manipulation functions.
Outline
4 #include <iostream>
5 using std::cout;
6 using std::endl;
Fig23_15.cpp
7 <algorithm> must be included
8 #include <vector> // vector class-template definition
to use STL algorithms(1 of 3)
9 #include <algorithm> // copy algorithm
10 #include <iterator> // ostream_iterator iterator
11 #include <stdexcept> // out_of_range exception Initializeintegers with the contents
12
of array from location array up to
13 int main()
14 {
just before location array + SIZE
15 const int SIZE = 6;
16 int array[ SIZE ] = { 1, 2, 3, 4, 5, 6 };
output can be used to output integers
17 std::vector< int > integers( array, array + SIZE );
18 std::ostream_iterator< int > output( cout, " " );
separated by single spaces via cout
19
20 cout << "Vector integers contains: "; Copy the entire contents of vector
21 std::copy( integers.begin(), integers.end(), output ); integers to the standard output
22
23 cout << "\nFirst element of integers: " << integers.front()
24 << "\nLast element of integers: " << integers.back();
References to first and last
25 elements of integers
26 integers[ 0 ] = 7; // set first element to 7
27 integers.at( 2 ) = 10; // set element at position 2 to 10 Access individual elements of integers
28
29 // insert 22 as 2nd element
30 integers.insert( integers.begin() + 1, 22 ); Insert 22 as the second element
 2006 Pearson Education,
Inc. All rights reserved.
31
39
32
33
cout << "\n\nContents of vector integers after changes: ";
std::copy( integers.begin(), integers.end(), output );
Outline
34
35 // access out-of-range element
36 try Member function at throws an
Fig23_15.cpp
37 { out_of_range exception
38 integers.at( 100 ) = 777;
39 } // end try
(2 of 3)
40 catch ( std::out_of_range outOfRange ) // out_of_range exception
41 {
42 cout << "\n\nException: " << outOfRange.what();
43 } // end catch
44
45 // erase first element Remove the element at the
46 integers.erase( integers.begin() ); beginning of integers
47 cout << "\n\nVector integers after erasing first element: ";
48 std::copy( integers.begin(), integers.end(), output );
49
50 // erase remaining elements Erase all elements of integers
51 integers.erase( integers.begin(), integers.end() );
52 cout << "\nAfter erasing all elements, vector integers "
53 << ( integers.empty() ? "is" : "is not" ) << " empty";
54
Confirm that the vector is empty
55 // insert elements from array
56 integers.insert( integers.begin(), array, array + SIZE );
57 cout << "\n\nContents of vector integers before clear: ";
58 std::copy( integers.begin(), integers.end(), output ); Insert all of array at the
beginning of integers

 2006 Pearson Education,


Inc. All rights reserved.
59
40
60 // empty integers; clear calls erase to empty a collection
Outline
61 integers.clear();
62 cout << "\nAfter clear, vector integers " Empty the vector
63 << ( integers.empty() ? "is" : "is not" ) << " empty" << endl;
64 return 0; Fig23_15.cpp
65 } // end main
(3 of 3)
Vector integers contains: 1 2 3 4 5 6
First element of integers: 1
Last element of integers: 6

Contents of vector integers after changes: 7 22 2 10 4 5 6

Exception: invalid vector<T> subscript

Vector integers after erasing first element: 22 2 10 4 5 6


After erasing all elements, vector integers is empty

Contents of vector integers before clear: 1 2 3 4 5 6


After clear, vector integers is empty

 2006 Pearson Education,


Inc. All rights reserved.
41

STL exception types Description

out_of_range Indicates when subscript is out of range—e.g., when an


invalid subscript is specified to vector member function
at.
invalid_argument Indicates an invalid argument was passed to a function.
length_error Indicates an attempt to create too long a container, string,
etc.
bad_alloc Indicates that an attempt to allocate memory with s (or with
an allocator) failed because not enough memory was
available.

Fig. 23.16 | Some STL exception types.

 2006 Pearson Education, Inc. All rights reserved.


42

23.2.2 list Sequence Container


• Class template list
– Implemented as a doubly-linked list
• Provides efficient insertion and deletion operations at any
location
– Supports bidirectional iterators
• Can be traversed forward and backward
– Requires header file <list>

 2006 Pearson Education, Inc. All rights reserved.


43

23.2.2 list Sequence Container (Cont.)

• Class template list (Cont.)


– Member function sort
• Arranges the elements in the list in ascending order
• Can take a binary predicate function as second argument to
determine sorting order
– Member function splice
• Removes elements from the container argument and inserts
them into the current list at the specified location
• Overloaded versions
– Three arguments - third argument specifies a single
element in the container argument to splice
– Four arguments - third and fourth arguments specify a
range of elements in the container argument to splice

 2006 Pearson Education, Inc. All rights reserved.


44

23.2.2 list Sequence Container (Cont.)

• Class template list (Cont.)


– Member function merge
• Removes elements from the specified list and inserts them
in sorted order into the current list
– Both lists must first be sorted in the same order
• Can take a binary predicate function as second argument to
determine sorting order
– Member function unique
• Removes duplicate elements from the list
– list must first be sorted
• A second argument can specify a binary predicate function to
determine whether two elements are equal

 2006 Pearson Education, Inc. All rights reserved.


45

23.2.2 list Sequence Container (Cont.)

• Class template list (Cont.)


– Member function assign
• Replaces contents of the current list with values from the
range specified by two iterator arguments
• Overloaded version
– Replaces contents with copies of a value
• First argument specifies number of copies
• Second argument specifies the value to assign

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.17: Fig23_17.cpp
46
2
3
// Standard library list class template test program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
Fig23_17.cpp
7 #include <list> // list class-template definition
8 #include <algorithm> // copy algorithm
9 #include <iterator> // ostream_iterator
(1 of 5)
10
11 // prototype for function template printList
12 template < typename T > void printList( const std::list< T > &listRef );
13
14 int main()
15 {
16 const int SIZE = 4;
17 int array[ SIZE ] = { 2, 6, 4, 8 };
18 std::list< int > values; // create list of ints Instantiate two list objects
19 std::list< int > otherValues; // create list of ints capable of storing integers
20
21 // insert items in values
22 values.push_front( 1 );
23 values.push_front( 2 ); Insert integers at the beginning and end of values
24 values.push_back( 4 );
25 values.push_back( 3 );
26
27 cout << "values contains: ";
28 printList( values );

 2006 Pearson Education,


Inc. All rights reserved.
29
47
30
31
values.sort(); // sort values
cout << "\nvalues after sorting contains: "; Arrange the elements in the
Outline
32 printList( values ); list in ascending order
33
34 // insert elements of array into otherValues
Fig23_17.cpp
35 otherValues.insert( otherValues.begin(), array, array + SIZE );
36 cout << "\nAfter insert, otherValues contains: ";
37 printList( otherValues );
(2 of 5)
38
39 // remove otherValues elements and insert at end of values
40 values.splice( values.end(), otherValues );
41 cout << "\nAfter splice, values contains: "; Remove the elements in otherValues
42 printList( values ); and insert them at the end of values
43
44 values.sort(); // sort values
45 cout << "\nAfter sort, values contains: ";
46 printList( values );
47
48 // insert elements of array into otherValues
49 otherValues.insert( otherValues.begin(), array, array + SIZE );
50 otherValues.sort();
51 cout << "\nAfter insert, otherValues contains: ";
52 printList( otherValues );

 2006 Pearson Education,


Inc. All rights reserved.
53
48
54
55
// remove otherValues elements and insert into values in sorted order
values.merge( otherValues );
Outline
56 cout << "\nAfter merge:\n values contains: ";
Remove all elements of otherValues and
57 printList( values );
58 cout << "\n otherValues contains: ";
insert them in sorted order in values
Fig23_17.cpp
59 printList( otherValues );
60
61 values.pop_front(); // remove element from front
(3 of 5)
62 values.pop_back(); // remove element from back
63 cout << "\nAfter pop_front and pop_back:\n values contains: "
64 printList( values );
65 Remove duplicate elements in values
66 values.unique(); // remove duplicate elements
67 cout << "\nAfter unique, values contains: ";
68 printList( values );
69
70 // swap elements of values and otherValues Exchange the contents of values with
71 values.swap( otherValues );
the contents of otherValues
72 cout << "\nAfter swap:\n values contains: ";
73 printList( values );
74 cout << "\n otherValues contains: ";
75 printList( otherValues );
76
77 // replace contents of values with elements of otherValues
78 values.assign( otherValues.begin(), otherValues.end() );
79 cout << "\nAfter assign, values contains: ";
80 printList( values ); Replace the contents of values with
the elements in otherValues

 2006 Pearson Education,


Inc. All rights reserved.
81
49
82
83
// remove otherValues elements and insert into values in sorted order
values.merge( otherValues );
Outline
84 cout << "\nAfter merge, values contains: ";
85 printList( values ); Delete all copies of the
86 value 4 from values
Fig23_17.cpp
87 values.remove( 4 ); // remove all 4s
88 cout << "\nAfter remove( 4 ), values contains: ";
89 printList( values );
(4 of 5)
90 cout << endl;
91 return 0;
92 } // end main
93
94 // printList function template definition; uses
95 // ostream_iterator and copy algorithm to output list elements
96 template < typename T > void printList( const std::list< T > &listRef )
97 {
98 if ( listRef.empty() ) // list is empty
99 cout << "List is empty";
100 else
101 {
102 std::ostream_iterator< T > output( cout, " " );
103 std::copy( listRef.begin(), listRef.end(), output );
104 } // end else
105 } // end function printList

 2006 Pearson Education,


Inc. All rights reserved.
values contains: 2 1 4 3 50
values after sorting contains: 1 2 3 4 Outline
After insert, otherValues contains: 2 6 4 8
After splice, values contains: 1 2 3 4 2 6 4 8
After sort, values contains: 1 2 2 3 4 4 6 8
After insert, otherValues contains: 2 4 6 8
After merge: Fig23_17.cpp
values contains: 1 2 2 2 3 4 4 4 6 6 8 8
otherValues contains: List is empty
After pop_front and pop_back: (5 of 5)
values contains: 2 2 2 3 4 4 4 6 6 8
After unique, values contains: 2 3 4 6 8
After swap:
values contains: List is empty
otherValues contains: 2 3 4 6 8
After assign, values contains: 2 3 4 6 8
After merge, values contains: 2 2 3 3 4 4 6 6 8 8
After remove( 4 ), values contains: 2 2 3 3 6 6 8 8

 2006 Pearson Education,


Inc. All rights reserved.
51

23.2.3 deque Sequence Container


• Class template deque
– Provides many of the benefits of vector and list in one
container
• Efficient indexed access using subscripting
• Efficient insertion and deletion operations at front and back
– Supports random-access iterators
• All STL algorithms can be used on deques
– Additional storage may be allocated at either end
• Noncontiguous memory layout
– Requires header file <deque>

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.18: Fig23_18.cpp
52
2
3
// Standard Library class deque test program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
Fig23_18.cpp
7 #include <deque> // deque class-template definition
8 #include <algorithm> // copy algorithm
9 #include <iterator> // ostream_iterator
(1 of 2)
10 Instantiate a deque that can
11 int main()
store double values
12 {
13 std::deque< double > values; // create deque of doubles
14 std::ostream_iterator< double > output( cout, " " );
15
16 // insert elements in values
Insert elements at the beginning
17 values.push_front( 2.2 );
and end of the deque
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 ] << ' '; Retrieve the value in each element
26 of the deque for output
27 values.pop_front(); // remove first element
28 cout << "\nAfter pop_front, values contains: "; Remove the first element of the deque
29 std::copy( values.begin(), values.end(), output );

 2006 Pearson Education,


Inc. All rights reserved.
30
53
31
32
// use subscript operator to modify element at location 1
values[ 1 ] = 5.4;
Outline
33 cout << "\nAfter values[ 1 ] = 5.4, values contains: "; Use the subscript operator
34 std::copy( values.begin(), values.end(), output ); to create an lvalue
35 cout << endl;
Fig23_18.cpp
36 return 0;
37 } // end main
(2 of 2)
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

 2006 Pearson Education,


Inc. All rights reserved.
54

23.3 Associative Containers


• STL associative containers
– Provide direct access to store and retrieve elements via
keys (often called search keys)
• Maintain keys in sorted order
– Four associative containers
• multiset – stores keys only, allows duplicates
• set – stores keys only, no duplicates
• multimap – stores keys and associated values, allows
duplicates
• map – stores keys and associated values, no duplicates
– Common member functions
• find, lower_bound, upper_bound, count

 2006 Pearson Education, Inc. All rights reserved.


55

23.3.1 multiset Associative Container

• multiset associative container


– Provides fast storage and retrieval of keys and allows
duplicate keys
– Ordering of keys is determined by a comparator function
object
• Default is std::less< T > for ascending order
• Data type of the keys must support this function
– Supports bidirectional iterators
– Requires header file <set>

 2006 Pearson Education, Inc. All rights reserved.


56
23.3.1 multiset Associative Container
(Cont.)
• multiset associative container (Cont.)
– Member function insert
• Adds a value to a set or multiset
• Overloaded versions
– Second version – an iterator argument specifies the
location to begin searching for the insertion point
– Third version – two iterator arguments specify a range
of values to add from another container
– Member function find
• Locates a value in the associative container
– Returns an iterator to its earliest occurrence
– Returns the iterator returned by end if the value is
not found

 2006 Pearson Education, Inc. All rights reserved.


57
23.3.1 multiset Associative Container
(Cont.)
• multiset associative container (Cont.)
– Member function lower_bound
• Locates earliest occurrence of a value
– Returns an iterator to that position
– Returns the iterator returned by end if the value is
not found
– Member function upper_bound
• Locates element after the last occurrence of a value
– Returns an iterator to that position
– Returns the iterator returned by end if the value is
not found

 2006 Pearson Education, Inc. All rights reserved.


58
23.3.1 multiset Associative Container
(Cont.)
• multiset associative container (Cont.)
– Member function equal_range
• Returns pair object containing the results of
lower_bound and upper_bound
– pair data member first stores lower_bound
– pair data member second stores upper_bound

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.19: Fig23_19.cpp
59
2
3
// Testing Standard Library class multiset
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
Fig23_19.cpp
7 #include <set> // multiset class-template definition
8
9 // define short name for multiset type used in this program
(1 of 3)
10 typedef std::multiset< int, std::less< int > > Ims;
11 Create a new type name for a multiset
12 #include <algorithm> // copy algorithm
of integers in ascending order
13 #include <iterator> // ostream_iterator
14
15 int main()
16 {
17 const int SIZE = 10;
18 int a[ SIZE ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 };
19 Ims intMultiset; // Ims is typedef for "integer multiset"
20 std::ostream_iterator< int > output( cout, " " ); Count the number of occurrences of
21 the value 15 in intMultiset
22 cout << "There are currently " << intMultiset.count( 15 )
23 << " values of 15 in the multiset\n";
24 Add the value 15 to
25 intMultiset.insert( 15 ); // insert 15 in intMultiset intMultiset twice
26 intMultiset.insert( 15 ); // insert 15 in intMultiset
27 cout << "After inserts, there are " << intMultiset.count( 15 )
28 << " values of 15 in the multiset\n\n";

 2006 Pearson Education,


Inc. All rights reserved.
29
60
30
31
// iterator that cannot be used to change element values
Ims::const_iterator result;
Outline
32
Locate the value 15
33 // find 15 in intMultiset; find returns iterator
34 result = intMultiset.find( 15 );
in intMultiset
Fig23_19.cpp
35
36 if ( result != intMultiset.end() ) // if iterator not at end
37 cout << "Found value 15\n"; // found search value 15
(2 of 3)
38
39 // find 20 in intMultiset; find returns iterator
40 result = intMultiset.find( 20 );
41
42 if ( result == intMultiset.end() ) // will be true hence
43 cout << "Did not find value 20\n"; // did not find 20
44
45 // insert elements of array a into intMultiset Insert the elements of array
46 intMultiset.insert( a, a + SIZE ); a into intMultiset
47 cout << "\nAfter insert, intMultiset contains:\n";
48 std::copy( intMultiset.begin(), intMultiset.end(), output );
Locate the earliest occurrence of the
49
value 22 in intMultiset
50 // determine lower and upper bound of 22 in intMultiset
51 cout << "\n\nLower bound of 22: "
52 << *( intMultiset.lower_bound( 22 ) );
53 cout << "\nUpper bound of 22: " << *( intMultiset.upper_bound( 22 ) );
54
55 // p represents pair of const_iterators
56 std::pair< Ims::const_iterator, Ims::const_iterator > p; Locate the position after the last
occurrence of the value 22 in
intMultiset
 2006 Pearson Education,
Inc. All rights reserved.
57
61
58
59
// use equal_range to determine lower and upper bound
// of 22 in intMultiset
Outline
Obtain the results of both a lower_bound
60 p = intMultiset.equal_range( 22 ); and an upper_bound operation from a
61 single function call
62 cout << "\n\nequal_range of 22:" << "\n Lower bound: "
Fig23_19.cpp
63 << *( p.first ) << "\n Upper bound: " << *( p.second );
64 cout << endl;
65 return 0;
(3 of 3)
66 } // end main
A pair contains two public data
There are currently 0 values of 15 in the multiset
After inserts, there are 2 values of 15 in the multiset
members, first and second

Found value 15
Did not find value 20

After insert, intMultiset contains:


1 7 9 13 15 15 18 22 22 30 85 100

Lower bound of 22: 22


Upper bound of 22: 30

equal_range of 22:
Lower bound: 22
Upper bound: 30

 2006 Pearson Education,


Inc. All rights reserved.
62

23.3.2 set Associative Container


• set associative container
– Used for fast storage and retrieval of unique keys
• Does not allow duplicate keys
– An attempt to insert a duplicate key is ignored
– Supports bidirectional iterators
– Requires header file <set>
– Member function insert
• Inserts a value into the set
• Returns a pair object
– pair member first is an iterator pointing to the
element with that value inside the set
– pair member second is a bool indicating whether
the value was inserted
 2006 Pearson Education, Inc. All rights reserved.
1 // Fig. 23.20: Fig23_20.cpp
63
2
3
// Standard Library class set test program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
Fig23_20.cpp
7 #include <set>
8
9 // define short name for set type used in this program
(1 of 2)
10 typedef std::set< double, std::less< double > > DoubleSet;
11
12 #include <algorithm>
Create a new type name for a set of
13 #include <iterator> // ostream_iterator
14
double values ordered in ascending order
15 int main()
16 {
17 const int SIZE = 5;
18 double a[ SIZE ] = { 2.1, 4.2, 9.5, 2.1, 3.7 }; Second 2.1 value (a duplicate)
19 DoubleSet doubleSet( a, a + SIZE );
will be ignored
20 std::ostream_iterator< double > output( cout, " " );
21
22 cout << "doubleSet contains: ";
23 std::copy( doubleSet.begin(), doubleSet.end(), output );
24
25 // p represents pair containing const_iterator and bool
26 std::pair< DoubleSet::const_iterator, bool > p;
Define a pair object to store the result
of set member function insert

 2006 Pearson Education,


Inc. All rights reserved.
27
64
28
29
// insert 13.8 in doubleSet; insert returns pair in which
// p.first represents location of 13.8 in doubleSet and
Outline
30 // p.second represents whether 13.8 was inserted
31 p = doubleSet.insert( 13.8 ); // value not in set Iterator p.first points to
32 cout << "\n\n" << *( p.first ) the value 13.8Fig23_20.cpp
in the set
33 << ( p.second ? " was" : " was not" ) << " inserted";
34 cout << "\ndoubleSet contains: ";
35 std::copy( doubleSet.begin(), doubleSet.end(), output );
(2 of 2) is true
bool value p.second
36 if the value was inserted
37 // insert 9.5 in doubleSet
38 p = doubleSet.insert( 9.5 ); // value already in set
39 cout << "\n\n" << *( p.first )
40 << ( p.second ? " was" : " was not" ) << " inserted";
41 cout << "\ndoubleSet contains: ";
42 std::copy( doubleSet.begin(), doubleSet.end(), output );
43 cout << endl;
44 return 0;
45 } // end main

doubleSet contains: 2.1 3.7 4.2 9.5

13.8 was inserted


doubleSet contains: 2.1 3.7 4.2 9.5 13.8

9.5 was not inserted


doubleSet contains: 2.1 3.7 4.2 9.5 13.8

 2006 Pearson Education,


Inc. All rights reserved.
65

23.3.3 multimap Associative Container

• multimap associative container


– Used for fast storage and retrieval of keys and associated
values (key/value pairs)
• Stored as pair objects
• Duplicate keys are allowed (one-to-many mapping)
– Multiple values can be associated with a single key
– Ordering of keys is determined by a comparator function
object
– Supports bidirectional iterators
– Requires header file <map>

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.21: Fig23_21.cpp
66
2
3
// Standard Library class multimap test program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl; Define an alias for a multimap type with int
6 keys and double values, in ascending order
Fig23_21.cpp
7 #include <map> // map class-template definition
8
9 // define short name for multimap type used in this program
(1 of 2)
10 typedef std::multimap< int, double, std::less< int > > Mmid; Determine the number of key/value
11
pairs with a key of 15
12 int main()
13 {
14 Mmid pairs; // declare the multimap pairs
15 Add new key/value pairs
16 cout << "There are currently " << pairs.count( 15 ) to the multimap
17 << " pairs with key 15 in the multimap\n";
18
19 // insert two value_type objects in pairs
20 pairs.insert( Mmid::value_type( 15, 2.7 ) );
Create a pair object in which first
21 pairs.insert( Mmid::value_type( 15, 99.3 ) );
22
is the int key 15 and second is
23 cout << "After inserts, there are " << pairs.count( 15 ) the double value 2.7
24 << " pairs with key 15\n\n";

 2006 Pearson Education,


Inc. All rights reserved.
25
67
26
27
// insert five value_type objects in pairs
pairs.insert( Mmid::value_type( 30, 111.11 ) );
Outline
28 pairs.insert( Mmid::value_type( 10, 22.22 ) );
29 pairs.insert( Mmid::value_type( 25, 33.333 ) );
30 pairs.insert( Mmid::value_type( 20, 9.345 ) );
Fig23_21.cpp
31 pairs.insert( Mmid::value_type( 5, 77.54 ) );
32
33 cout << "Multimap pairs contains:\nKey\tValue\n";
(2 of 2)
34
35 // use const_iterator to walk through elements of pairs
36 for ( Mmid::const_iterator iter = pairs.begin();
37 iter != pairs.end(); ++iter ) Use const_iterator iter to
38 cout << iter->first << '\t' << iter->second << '\n'; access the keys and values in pairs
39
40 cout << endl;
41 return 0;
42 } // end main

There are currently 0 pairs with key 15 in the multimap


After inserts, there are 2 pairs with key 15

Multimap pairs contains:


Key Value
5 77.54
10 22.22
15 2.7
15 99.3
20 9.345
25 33.333
30 111.11

 2006 Pearson Education,


Inc. All rights reserved.
68

23.3.4 map Associative Container


• map associative container
– Used for fast storage and retrieval of keys and associated
values (key/value pairs)
• Stored as pair objects
• Duplicate keys are not allowed (one-to-one mapping)
– Only one value can be associated with each key
– Commonly called an associative array
• Inserting a new key/value pair is called creating an
association
– Insertions and deletions can be made anywhere
– Requires header file <map>

 2006 Pearson Education, Inc. All rights reserved.


69

23.3.4 map Associative Container (Cont.)

• map associative container (Cont.)


– Subscript operator [] can locate the value associated with
a given key
• When the key is already in the map
– Returns a reference to the associated value
• When the key is not in the map
– Inserts the key in the map
– Returns a reference to the associated value (so it can be
set)

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.22: Fig23_22.cpp
70
2
3
// Standard Library class map test program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
Fig23_22.cpp
7 #include <map> // map class-template definition
8
9 // define short name for map type used in this program
(1 of 3)
10 typedef std::map< int, double, std::less< int > > Mid;
11
12 int main()
13 {
14 Mid pairs;
15
16 // insert eight value_type objects in pairs
17 pairs.insert( Mid::value_type( 15, 2.7 ) );
18 pairs.insert( Mid::value_type( 30, 111.11 ) );
19 pairs.insert( Mid::value_type( 5, 1010.1 ) );
20 pairs.insert( Mid::value_type( 10, 22.22 ) );
21 pairs.insert( Mid::value_type( 25, 33.333 ) );
22 pairs.insert( Mid::value_type( 5, 77.54 ) ); // dup ignored
23 pairs.insert( Mid::value_type( 20, 9.345 ) );
24 pairs.insert( Mid::value_type( 15, 99.3 ) ); // dup ignored
25
26 cout << "pairs contains:\nKey\tValue\n";

 2006 Pearson Education,


Inc. All rights reserved.
27
71
28 // use const_iterator to walk through elements of pairs
Outline
29 for ( Mid::const_iterator iter = pairs.begin();
30 iter != pairs.end(); ++iter )
31 cout << iter->first << '\t' << iter->second << '\n'; Replace the value for the key 25
32 with the new value 9999.99
Fig23_22.cpp
33 pairs[ 25 ] = 9999.99; // use subscripting to change value for key 25
34 pairs[ 40 ] = 8765.43; // use subscripting to insert value for key 40 (2 of 3)
35
36 cout << "\nAfter subscript operations, pairs contains:\nKey\tValue\n"; Insert a new key/value
37 pair in the map
38 // use const_iterator to walk through elements of pairs
39 for ( Mid::const_iterator iter2 = pairs.begin();
40 iter2 != pairs.end(); ++iter2 )
41 cout << iter2->first << '\t' << iter2->second << '\n';
42
43 cout << endl;
44 return 0;
45 } // end main

 2006 Pearson Education,


Inc. All rights reserved.
pairs contains:
72
Key Value Outline
5 1010.1
10 22.22
15 2.7
20 9.345
25 33.333 Fig23_22.cpp
30 111.11
(3 of 3)
After subscript operations, pairs contains:
Key Value
5 1010.1
10 22.22
15 2.7
20 9.345
25 9999.99
30 111.11
40 8765.43

 2006 Pearson Education,


Inc. All rights reserved.
73

23.4 Container Adapters


• STL container adapters
– Are not first-class containers
• Do not provide the actual data structure implementation
• Do not support iterators
– Programmer can choose an appropriate underlying data
structure
– Common member functions
• push
– Properly insert an element into data structure
• pop
– Properly remove an element from data structure

 2006 Pearson Education, Inc. All rights reserved.


74

23.4.1 stack Adapter


• Class stack
– Enables insertions and deletions at one end
• Last-in, first-out data structure
– Can be implemented with any sequence container
• Implemented with a deque by default
– Operations (call functions of the underlying container)
• push – insert element at top (calls push_back)
• pop – remove top element (calls pop_back)
• top – returns reference to top element (calls back)
• empty – determine if the stack is empty (calls empty)
• size – get the number of elements (calls size)
– Requires header file <stack>

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.23: Fig23_23.cpp
75
2
3
// Standard Library adapter stack test program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
Fig23_23.cpp
7 #include <stack> // stack adapter definition
8 #include <vector> // vector class-template definition
9 #include <list> // list class-template definition
(1 of 3)
10
11 // pushElements function-template prototype
12 template< typename T > void pushElements( T &stackRef );
13
14 // popElements function-template prototype
15 template< typename T > void popElements( T &stackRef );
16 Specify integer stacks using each of
17 int main() the three sequence containers as the
18 {
underlying data structure
19 // stack with default underlying deque
20 std::stack< int > intDequeStack;
21
22 // stack with underlying vector
23 std::stack< int, std::vector< int > > intVectorStack;
24
25 // stack with underlying list
26 std::stack< int, std::list< int > > intListStack;

 2006 Pearson Education,


Inc. All rights reserved.
27
76
28
29
// push the values 0-9 onto each stack
cout << "Pushing onto intDequeStack: ";
Outline
30 pushElements( intDequeStack );
31 cout << "\nPushing onto intVectorStack: ";
32 pushElements( intVectorStack );
Fig23_23.cpp
33 cout << "\nPushing onto intListStack: ";
34 pushElements( intListStack );
35 cout << endl << endl;
(2 of 3)
36
37 // display and remove elements from each stack
38 cout << "Popping from intDequeStack: ";
39 popElements( intDequeStack );
40 cout << "\nPopping from intVectorStack: ";
41 popElements( intVectorStack );
42 cout << "\nPopping from intListStack: ";
43 popElements( intListStack );
44 cout << endl;
45 return 0;
46 } // end main
47
48 // push elements onto stack object to which stackRef refers
49 template< typename T > void pushElements( T &stackRef )
Place an integer on
50 { top of the stack
51 for ( int i = 0; i < 10; i++ )
52 {
53 stackRef.push( i ); // push element onto stack
54 cout << stackRef.top() << ' '; // view (and display ) top element
55 } // end for
Retrieve, but not remove, the top element
56 } // end function pushElements

 2006 Pearson Education,


Inc. All rights reserved.
57
77
58
59
// pop elements from stack object to which stackRef refers
template< typename T > void popElements( T &stackRef )
Outline
60 {
61 while ( !stackRef.empty() ) Retrieve and display the top element
62 {
Fig23_23.cpp
63 cout << stackRef.top() << ' '; // view (and display) top element
64 stackRef.pop(); // remove top element
65 } // end while
(3 of 3)
66 } // end function popElements Remove, and discard, the top element
Pushing onto intDequeStack: 0 1 2 3 4 5 6 7 8 9
Pushing onto intVectorStack: 0 1 2 3 4 5 6 7 8 9
Pushing onto intListStack: 0 1 2 3 4 5 6 7 8 9

Popping from intDequeStack: 9 8 7 6 5 4 3 2 1 0


Popping from intVectorStack: 9 8 7 6 5 4 3 2 1 0
Popping from intListStack: 9 8 7 6 5 4 3 2 1 0

 2006 Pearson Education,


Inc. All rights reserved.
78

23.4.2 queue Adapter


• Class queue
– Enables insertions at back and deletions from front
• First-in, first-out data structure
– Can be implemented with data structure list or deque
• Implemented with a deque by default
– Operations (call functions of the underlying container)
• push – insert element at back (calls push_back)
• pop – remove element from front (calls pop_front)
• front – returns reference to first element (calls front)
• empty – determine if the queue is empty (calls empty)
• size – get the number of elements (calls size)
– Requires header file <queue>

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.24: Fig23_24.cpp
79
2 // Standard Library adapter queue test program.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 Fig23_24.cpp
7 #include <queue> // queue adapter definition
8 Instantiate a queue that (1 of 2)
9 int main() stores double values
10 {
11 std::queue< double > values; // queue with doubles
12
13 // push elements onto queue values
14 values.push( 3.2 );
Add elements to the queue
15 values.push( 9.8 );
16 values.push( 5.4 );
17
18 cout << "Popping from values: ";

 2006 Pearson Education,


Inc. All rights reserved.
19
80
20 // pop elements from queue
Read the first element in Outline
21 while ( !values.empty() )
the queue for output
22 {
23 cout << values.front() << ' '; // view front element
24 values.pop(); // remove element Fig23_24.cpp
25 } // end while
26 (2 of 2)
27 cout << endl;
Remove the first element
28 return 0;
in the queue
29 } // end main

Popping from values: 3.2 9.8 5.4

 2006 Pearson Education,


Inc. All rights reserved.
81

23.4.3 priority_queue Adapter


• Class priority_queue
– Enables insertions in sorted order and deletions from front
• Elements are inserted in priority order
• Highest-priority element will be the first to be removed
• Maintains sorted order via heapsort
– Heaps keep largest value at the front
– Comparison of elements is performed with comparator
function object less< T > by default
– Can be implemented with data structure vector or
deque
• Implemented with a vector by default

 2006 Pearson Education, Inc. All rights reserved.


82

23.4.3 priority_queue Adapter (Cont.)

• Class priority_queue (Cont.)


– Operations (call functions of the underlying container)
• push – insert element at appropriate location to maintain
sorted order (calls push_back, then reorders elements with
heapsort)
• pop – remove highest-priority element (moves top element of
heap to back, then calls pop_back)
• top – returns reference to top element (calls front)
• empty – determine if the priority_queue is empty (calls
empty)
• size – get the number of elements (calls size)
– Requires header file <queue>

 2006 Pearson Education, Inc. All rights reserved.


1 // Fig. 23.25: Fig23_25.cpp
83
2
3
// Standard Library adapter priority_queue test program.
#include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
7
Instantiate a priority_queue thatFig23_25.cpp
#include <queue> // priority_queue adapter definition
8 stores double values using a vector
9 int main() as the underlying data structure (1 of 1)
10 {
11 std::priority_queue< double > priorities; // create priority_queue
12
13 // push elements onto priorities
Add elements to the priority_queue
14 priorities.push( 3.2 );
15 priorities.push( 9.8 );
16 priorities.push( 5.4 );
17
18 cout << "Popping from priorities: ";
19 Retrieve the highest-priority element in
20 // pop element from priority_queue
the priority_queue for output
21 while ( !priorities.empty() )
22 {
23 cout << priorities.top() << ' '; // view top element
24 priorities.pop(); // remove top element
25 } // end while
26
27 cout << endl;
28 return 0; Remove the highest-priority element
29 } // end main in the priority_queue
Popping from priorities: 9.8 5.4 3.2
 2006 Pearson Education,
Inc. All rights reserved.

You might also like