Generic programming•Each iterator defines the operations that are needed to access the contents of a particular type of container.. The three sequential container types are: vector
Trang 1Chương 6
Standard Template Library
Trang 2The Standard Template Library
Trang 3The Standard Template Library
• The Standard Template Library (STL) is a general-purpose
library of container classes (such as vectors, lists, sets and
maps) and generic algorithms (such as searching, sorting
and merging)
• The chief difference between STL and other C++ libraries
is that STL containers and algorithms can be "plugged"
together in a myriad of different useful ways
Trang 4Problems with libraries
• Writing your own library of
container classes can be very
frustrating because, even if you
are familiar with the best
techniques, there is rarely time to implement them
• Buying a commercial library also has its drawbacks:
– Incompatibility
– Inefficiency
– Unwieldy interfaces
Trang 5Origins of STL
• In view of these problems, the
ANSI committee for C++
standardisation sought a
standard set of container classes
• Alexander Stepanov and Meng
Lee of Hewlett Packard
Laboratories proposed STL, and
in 1994 it was accepted as part of the C++ Standard Library.
Trang 6Why STL?
• STL was chosen as the ANSI
standard for several reasons:
Trang 7Generic programming
• Research into generic
programming has aimed to
produce libraries of generic, or
reusable, software components
Trang 8
Generic programming
•Each iterator defines the
operations that are needed to
access the contents of a
particular type of container
•Class templates are used to
define containers and iterators, and function templates are used
to define generic algorithms
Trang 9Generic programming
•Not every generic algorithm
and iterator can be plugged
together STL prohibits some
combinations because certain algorithms are only efficient
when they are used with
certain types of containers
Trang 11• A container is a data structure
that stores a collection of
Trang 12Sequential containers
• Sequential containers store
items in a linear structure
The three sequential
container types are:
vector <T>
deque <T>
list <T>
Trang 13Associative containers
• Associative containers store
items in a structure suited for
fast associative lookup The four associative container types are:
set <Key>
multiset <Key>
map <Key, T>
multimap <Key, T>
Trang 14Generic algorithms (I)
• In traditional container class libraries, all of the algorithms
associated with a particular class are implemented as member functions of that class
• In contrast, most STL algorithms are written as external
functions that interact with container classes via iterators.
Trang 15Generic algorithms (II)
• Each algorithm can operate on a
variety of containers.
• By plugging together different
combinations of algorithms and containers you can create the
specialised components that are found in other software libraries
Trang 16char string1[ ] = "Central Queensland";
int length = strlen(string1);
// Reverse the array
std::reverse(&string1[0], &string1[length]);
// Check that the reversal was successful
assert(strcmp(string1, "dnalsneeuQ lartneC") == 0);
}
Trang 17#include <algorithm>
#include <vector>
#include <cassert>
using namespace::std;
// Return aVector containing the characters of aString
// (not including the terminating null character).
vector<char> getVector(char* aString)
Trang 18// Check that the reversal was successful
assert(vector1 == getVector("dnalsneeuQ lartneC"));
return 0;
}
Trang 19• Iterators are pointer-like objects that can be used to visit the
individual elements of a container
• STL algorithms are written in terms of iterator parameters, and
STL containers provide the iterators that can be plugged into
those algorithms
• Each STL container type C defines C::iterator as an iterator type that can be used with type C containers
Trang 20#include <algorithm>
#include <vector>
#include <iostream>
using namespace::std;
// Return aVector containing the characters of aString
// (not including the terminating null character)
vector<char> getVector(char* aString)
Trang 21// Display the contents of the vector
for (i = vector1.begin(); i != vector1.end(); i++)
cout << *i; cout << endl;
return 0; }
Trang 22Adaptors (I)
• An STL adaptor is a component that modifies the interface of
another component
• Adaptors are defined as class templates that accept a
component type as a parameter
Trang 23Adaptors (II)
• STL defines three kinds of
adaptors: container adaptors,
iterator adaptors, and function
adaptors
• Container adaptors change the
interface of a container Iterator
adaptors change the interface of
an iterator Function adaptors
change the interface of a function object
Trang 24• A stack is a container adaptor that
makes an ordinary sequential
container behave like a stack
• The stack container adaptor can
be applied to a vector, a deque or
a list:
– stack<vector<T>> is a stack of type
T with a vector implementation
– stack<deque<T>> is a stack of type
T with a deque implementation
Stack Adaptor (I)
Trang 25Stack Adaptor (II)
– stack<list<T>> is a stack of
implementation
• The stack adaptor modifies
the container's behaviour by
restricting its interface to just
push and pop operations.
Trang 26Function objects
• Function objects allow functions
to be encapsulated and
associated with data They also
allow functions to be created,
stored, and destroyed just like
any other kind of object
• Many STL containers and
algorithms use function objects
to perform their duties
Trang 27• A function object encapsulates a function in an object for use by
other components
• In C++ programming, we define a function object to be an
instance of any class that overloads the function call operator ().
Trang 28• The sort() algorithm can be called with
an optional function object argument
that tells it how to compare two objects
Trang 29• Allocators store information about particular memory models e.g 16-bit, 32-bit
• An STL container can be made to work with a particular memory model simply by passing it a suitable allocator as a template parameter
template <class T, class Allocator = allocator> class vector;
Trang 30STL header files
• If you want to use STL
components in your program, you must include one or more header
• The naming and organisation of
those header files will depend on whether you are using an
implementation that conforms to the ANSI C++ standard or the HP reference implementation of STL
Trang 31Header files in the standard implementation
• The sequential container class named c is in <c> For
example, vector is in <vector>, list is in <list>, and so on
• The associative container classes set and multiset are in
<set>.
• The associative container classes map and multimap are in
<map>.
• Generic algorithms are in <algorithm>, except generalised
numeric algorithms, which are in <numerics>.
• The stack container adaptor is in <stack>.
• The queue and priority_queue container adaptors are in
<queue>.
• Stream iterator classes and iterator adaptors are in <iterator>.
• Function objects and function adaptors are in <functional>.
Trang 32Header files in the HP reference
implementation
• The container class named c is in <c.h> For example, vector is in <vector.h>, list is in <list.h>, and so on
• Generic algorithms are in <algo.h>
• Container adaptors (stack, queue and priority_queue) are in <stack.h>
• Stream iterator classes and iterator adaptors are in <iterator.h>
• Function objects and function adaptors are in <function.h>
Trang 33Using STL with Borland/Turbo C++ 4.5
• If you are using either Borland C++ 4.5 or Turbo C++ 4.5 you must make the following
adjustments to any files that use STL:
– Include STL header files before Borland header
Trang 34-vi-Conventions used in
examples
• All of the examples in these lectures are compatible with the ANSI
C++ standard
• If you want to compile the examples with the HP reference
implementation of STL running on either Borland C++ 4.5 or Turbo C++ 4.5 :
• Add #define MINMAX_DEFINED and #pragma option -vi-
directives;
• remove the using namespace std declaration; and
• make minor adjustments to the #include directives
Trang 35The following code works with Borland C++ 4.5
// Return aVector containing the characters of aString
// (not including the terminating null character)
vector<char> getVector(char* aString)
Trang 36void main()
{
vector<char> vector1 = getVector("Central
Queensland");
vector<char>::iterator i;
// Reverse the vector
reverse(vector1.begin(), vector1.end());
// Display the contents of the vector
for (i = vector1.begin(); i != vector1.end(); i++) cout << *i;
cout << endl;
}
Trang 37STL containers and iterators
• Sequential containers
• Iterators
• Associative containers
Trang 39• A vector is a sequential container that is very
similar to a regular C++ array, except that it
can expand to accommodate new elements
• Vectors provide fast random access to their
elements
Trang 40• Insertions and deletions at the end of a
vector can be performed very quickly
• Inserting or deleting elements at any other
position is quite slow, so vectors should
be avoided if this kind of operation is
common
Trang 41• A deque is a sequential container that is
very similar to a vector, except in terms of performance and memory allocation.
• Elements can be inserted and deleted very
efficiently at either end of a deque
Trang 42• Most other deque operations are slightly
slower than the corresponding vector operations
• Inserting or deleting elements in the
middle of a deque is quite slow, so deques should be avoided if this kind of operation is common
Trang 43• Unlike vectors and deques, lists are
implemented as doubly-linked lists
• The advantage of a list is that the time it
takes to insert or delete an element is
constant regardless of the element's
position
Trang 44• The disadvantage of a list is that it
doesn’t fully support random access, which generic algorithms such as sort(), splice() and merge() rely on These
operations are provided as member functions of the list class instead
Trang 45• Lists are useful when you're performing a lot
of arbitrary insertions and deletions, but
they're not as efficient as deques when you're inserting or deleting elements at either the
start or end, and they're not as efficient as
vectors when you're inserting or deleting
elements at the end only.
Trang 46Vector functions
• The simplest sequential container, the
vector, will be used to illustrate the
functions that are common to all STL
containers
Trang 47Vector constructors
• vector()
Constructs an empty vector
• vector(size_type n)
Constructs a vector containing n elements set to their default values
• vector(size_type n, const T& value)
Constructs a vector containing n elements initialised to value
• vector(const T* first, const T* last)
Constructs a vector containing copies of all the elements in the range [first, last)
Trang 48Vector copy constructor and
destructor
• vector(const vector<T>& aVector)
Constructs a vector as a copy of aVector
• ~vector()
Destroys the vector and all of its elements
Trang 49Vector insertion
• void push_back(const T& value)
Adds value to the end of the vector, expanding storage to accommodate the new element if necessary.
• iterator insert(iterator pos, const T& value)
Inserts a copy of value at pos and returns an iterator pointing to the new element's position.
• void insert(iterator pos, size_type n, const T& value)
Inserts n copies of value at pos.
• void insert(iterator pos, const T *first, const T *last)
Inserts copies of the elements in the range [first, last) at pos
Trang 50Vector deletion
• void pop_back()
Deletes the vector's last element
• void erase(iterator pos)
Deletes the element at pos
• void erase(iterator first, iterator last)
Deletes the elements in the range [first, last)
Trang 51Vector accessor functions
• T& back()
Returns a reference to the vector's last element
• T& front()
Returns a reference to the vector's first element
• T& operator[](int index)
Returns a reference to the vector's index-th element
• bool empty() const
Returns true if the vector contains no elements
Trang 52Vector accessor functions 2
• size_type max_size() const
Returns the maximum number of elements the vector can contain
• size_type size() const
Returns the number of elements the vector contains
Trang 53Vector relational operators
• The == operator and the < operator let you compare vectors The !=, >, <= and >= operators
are all defined in terms of the == and < operators
• bool operator==(const vector aVector) const
Returns true if the vector contains the same elements in the same order as aVector
• bool operator<(const vector& aVector) const
Returns true if the vector is lexicographically less than aVector
Trang 54Vector assignment and exchange
• vector<T>& operator=(const vector<T>& aVector)
Replaces the contents of the vector with the contents of aVector
• void swap(vector<T>& aVector)
Swap the contents of the vector with the contents of aVector
Trang 55#include <vector>
#include <iostream>
// Displays the contents of a vector of integers
void display(const vector<int> v);
Trang 56// Insert 22 at the end of the vector
Trang 57// Remove the element at the end of the vector
Trang 58// Displays the contents of a vector of integers
void display(const vector<int> v)
Trang 59Deque functions
• A deque has almost the same interface as a vector The additional functions described
below take advantage of the deque's ability to perform insertions and deletions
efficiently at the beginning of the structure
• void push_front(const T& value)
Inserts a copy of value in front of the deque's first element
• void pop_front()
Deletes the deque's first element
Trang 60#include <deque>
#include <iostream>
// Displays the contents of a deque of characters
void display(const deque<char> d);
Trang 61// Insert three c's at the end of the deque
Trang 62// Displays the contents of a deque of characters
void display(const deque<char> d)
for(int i = 0; i <= d.size() - 1; i++)
cout << d[i] << ' '; cout << endl;
}
}
Example 2 3
Trang 63List functions
• Since lists do not have random access iterators, some generic algorithms such as sort() are provided as member functions of the list class
Trang 64List functions 1
• void splice(iterator pos, list<T>& aList)
Deletes all of the elements from aList and inserts them before position pos
• void splice(iterator to, list<T>& aList, iterator from)
Deletes the element in aList at position from and inserts it at position to
• void splice(iterator pos, list<T>& aList, iterator first, iterator last)
Deletes the elements from aList in the range [first, last) and inserts them at position pos
Trang 65List functions 2
• void remove(const T& value)
Deletes all elements from the list that match value.