DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
-
Upload
william-parks -
Category
Documents
-
view
227 -
download
5
Transcript of DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
![Page 1: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/1.jpg)
DATA STRUCTURES
ANDALGORITHMS
Lecture Notes 12
Prepared by İnanç TAHRALI
![Page 2: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/2.jpg)
2
ROAD MAP The Standart Template Library (STL)
Introduction Basic STL Concepts Unordered Sequences : vector and list Sets Maps Examples
![Page 3: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/3.jpg)
3
Introduction to STL
STL is a part of C++ library STL provides a collection of data
structures (such as lists, stacks, queues) and algorithms (sorting, selection)
STL does not provide hash table or a union/find data structure
![Page 4: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/4.jpg)
4
Basic STL Concepts
Header files and using Directive Containers iterator Pairs Function Objects
![Page 5: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/5.jpg)
5
Header file and using Directive Historically, the names of library header
files have ended with the .h suffix The new standart mandates that these
names are suffix-free Standard I/O file is iostream instead of
iostream.h iostream.h may not be compatible with STL
version Some of the other header files are
fstream, sstream, vector, list, deque, set and map
![Page 6: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/6.jpg)
6
Header file and using Directive
New standard adds a feature called namespace
The entire STL is defined in std namespace
To access the STL, we provide a using directive using namespace std
![Page 7: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/7.jpg)
7
A simple example#include <iostream>using namespace std;
int main(){cout << “First program” >> endl;return 0;
}
![Page 8: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/8.jpg)
8
Containers A container represents a group of
objects, known as its elements. Implementations may vary
vector and list implementations are unordered
sets and maps are ordered some implementations allow
dublicates others do not
![Page 9: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/9.jpg)
9
Containers All containers support the following
operations bool empty () const
returns true if the container contains no elements and false otherwise
iterator begin () const returns an iterator that can be used to begin
traversing all locations in the container iterator end () const
returns and iterator that represents the “end marker”, or a position past the last element in the container
int size () const returns the number of elements in the container
![Page 10: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/10.jpg)
10
iterator
An iterator is an object that allows us to iterate through all objects in a collection
Using an iterator class was discussed in linked lists.
STL iterator use the same general concepts but provide more power.
![Page 11: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/11.jpg)
11
iterator Following operations are available for any
iterator type itr ++
advances the iterator itr to the next location *itr
returns a reference to the object stored at iterator itr’s location
itr1 == itr2 returns true if itr1 and itr2 refer to the same location
and false otherwise itr1 != itr2
returns true if itr1 and itr2 refer to a different location and false otherwise
![Page 12: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/12.jpg)
12
iterator Each container defines several iterators
A list<int> defines list<int>::iterator and list<int>::const_iterator
The const_iterator must be used if container is nonmodifiable
Example// print the contents of a Container C
template <class Container>
void printCollection( const Container & C ) {
Container :: const_iterator itr;
for ( itr = c.begin () ; itr != C.end () ; itr ++ )
cout << *itr << ‘\n’;
}
![Page 13: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/13.jpg)
13
Pairs Often it is necessary to store a pair of
objects in a single entity It is useful for returning two things
simultaneously STL defines a class template pair as
followingtemplate <class Object1, class Object2>
class Pair
{
public :
Object1 first;
Obejct2 second;
}
![Page 14: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/14.jpg)
14
Function Objects Container algorithms that require an
ordering property generally use a default order
typically the less function (<)
But when the natural ordering is not exactly what is needed, different ordering propoerties can be specified to sort strings by length to sort vector of strings but ignore case
distinctions
![Page 15: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/15.jpg)
15
Function Objects• Following example compares strings by length• This function is passed as the optional third parameter to sort in the form
of an object• Although this function contains no data members and no contructors,
more general function objects are possible.• The only requirement is that operator () must be defined.• STL provides numerous template function objects including less or
greater
class Comp {
public :
bool operator() ( const string & lhs,
const string & lhs ) const
{ return lhs.length () < rhs.length (); }
};
void sortListOfStringsByLength ( vector <string> & array ){
sort (array.begin(), array.end(), Comp() );
}
![Page 16: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/16.jpg)
16
ROAD MAP The Standart Template Library (STL)
Introduction Basic STL Concepts Unordered Sequences : vector and
list Sets Maps Examples
![Page 17: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/17.jpg)
17
Unordered Sequences vector and list can be used to
implement an unordered container. The user controls where each
element is inserted in the sequence The user can access elements in the
sequence by position or search them Depending on particular operation,
only one of vector or list might be efficient
![Page 18: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/18.jpg)
18
vector versus list STL provides three sequence
implementations but only two are generally used Array based version
If insertions are performed only at the high end of the array
STL doubles the array if an insertion at the high end would exceed internal capacity
Expensive to constuct for large ojects
Doubly-linked list version Minimize calls to contructors
![Page 19: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/19.jpg)
19
vector versus list Insertions and deletions toward the middle
of the sequence are inefficient in vector A vector allows direct access by index but
a list does not List can be safely used unless indexing is
needed Vector is a good choise if
insertions occur only at the end objects being inserted are not overly
expensive to construct
![Page 20: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/20.jpg)
20
Operations on sequences void push_back ( const Object & element )
Appends elements at the end of the sequence void push_front ( const Object & element )
Prepends elements to the front of this sequence Not available for vector because it is too inefficient A deque is available that is like a vector but supports
double-ended access Object & front ( ) const
Returns the first element in the sequence Object & back ( ) const
Returns the last element in the sequence
![Page 21: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/21.jpg)
21
Operations on sequences void pop_front ( )
Removes the first element from the sequence void pop_back ( )
Removes the last element from the sequence iterator insert ( iterator pos, const Object & obj )
Inserts obj prior to the element in the position referred to by pos Takes constant time for a list, takes time proportional to distance
from pos to the end of the sequence for a vector Returns the position of the newly inserted item
iterator erase ( iterator pos ) Removes the object at the position referred by pos Takes constant time for lists, takes time to proportional to the
distance from pos to the end of the sequence for a vector Returns the position of the element that followed pos prior to the
call to erase
![Page 22: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/22.jpg)
22
Example/* A program that reads integers from the standard
inputs and outputs them in sorted order */
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main( ) {
vector<int> v; // Initial size is 0
int x;
while( cin >> x )
v.push_back( x );
sort( v.begin( ), v.end( ) );
for( int i = 0; i < v.size( ); i++ )
cout << v[ i ] << endl;
return 0;
}
![Page 23: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/23.jpg)
23
Stacks and Queues
STL provides a stack and queue class but these simply use a sequence container (list, vector or deque)
The queue does not even use standard names such as enqueue and dequeue
So sequence containers can be used directly
![Page 24: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/24.jpg)
24
// Queue class implemented using the STL list
#include <list>
using namespace std;
template <class Object>
class Queue
{
public:
bool isEmpty( ) const;
const Object & getFront( ) const;
void makeEmpty( );
Object dequeue( );
void enqueue( const Object & x );
private:
list<Object> theList;
};
![Page 25: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/25.jpg)
25
// Queue class implemented using the STL list
template <class Object>
bool Queue<Object>::isEmpty( ) const {
return theList.empty( );
}
template <class Object>
const Object & Queue<Object>::getFront( ) const {
if( isEmpty( ) )
throw Underflow( );
return theList.front( );
}template <class Object>void Queue<Object>::makeEmpty( ) {
while( !isEmpty( ) ) dequeue( );}template <class Object>Object Queue<Object>::dequeue( ) {
Object frontItem = getFront( ); theList.pop_front( ); return frontItem;}template <class Object>void Queue<Object>::enqueue( const Object & x ) {
theList.push_back( x ); }
![Page 26: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/26.jpg)
26
Sets
Set is an ordered container It alows no dublicates The underlying implementation is a
balanced search tree In addition usual begin, end, size
and empty, the set provides the following operations
![Page 27: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/27.jpg)
27
Set operations pair<iterator,bool> insert ( const Object &
element ) adds element to the set if it is not already present bool component is true if the set did not already
contain element; otherwise false iterator component of return value is the location of
element in the set iterator find (const Object & element ) const
returns the location of element in the set int erase (const Object & element)
removes element from the set if it is present returns the number of elements removed ( either 0
or 1 )
![Page 28: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/28.jpg)
28
// illustration of set, using reverse order
#include <iostream>#include <set>#include <string>using namespace std;
int main( ){
set<string, greater<string> > s; // Use reverse order
s.insert( "joe" );s.insert( "bob" );printCollection( s );return 0;
}
Example
![Page 29: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/29.jpg)
29
Maps A map is used to store a collection of
ordered entries that consists of keys and their values
Keys must be unique Several keys can map to the same values
Values need not be unique The map uses a balanced search tree
to obtain logarithmic search times
![Page 30: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/30.jpg)
30
Maps The map behaves like a set instantiated
with a pair, whose comparison function refers only to the key It supports begin, end, size, empty The underlying iterator is a key-value pair.
The map supports insert, find and erase For insert, we must provide a pair <KeyType,ValueType> object
Find requires only a key, the iterator it returns references a pair
![Page 31: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/31.jpg)
31
Maps The map has an important extra operation The array-indexing operation is overloaded for
maps
ValueType & operator [] ( const KeyType & key )const ValueType & operator [] ( const KeyType & key ) const
Either of these functions returns value to which this key is mapped by the map
If key is not mapped, then becomes mapped to a default ValueType generating by constructor
![Page 32: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/32.jpg)
32
Maps
Illustration of the map : Tim’s value is 5; Bob’s value is 0
![Page 33: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/33.jpg)
33
ROAD MAP The Standart Template Library (STL)
Introduction Basic STL Concepts Unordered Sequences : vector and list Sets Maps Examples
![Page 34: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/34.jpg)
34
Example :Generating a Concordance
A concordance of a file is a listing that contains all the words in a file
with line number on which the word occurs We can use a map to map words to a list of lines on
which the word occurs Each key is a word, its value is a list of line numbers When we see a word, we check if it is already in map If it is, we add the current line number to the list of lines
that corresponds to the word If it is not, we add to the map the word along with a list
contaning the current line number After we have read all words, we can iterate through the
map This generates the map entries in key-sorted order For each map entry we output the word We go through the linked list of line numbers and output
them
![Page 35: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/35.jpg)
35
Example : Generating a Concordance
![Page 36: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/36.jpg)
36
Example :Generating a Concordance
What about the version without using STL ?
![Page 37: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/37.jpg)
37
Version without using STL There are three basic differences : The text’s classes do not directly implement a
map We must use a search tree containing entries that
store a stirng and a List, with the string as the key This entry will be a WordEntry object
The list class is singly linked and does not have a built-in method to insert at the end
WordEntry will need to maintain an iterator that represents the last entry in its linked list
There is no tree iterator There is a printTree method
![Page 38: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/38.jpg)
38
Example :Shortest Path Calculation We provide implementation of unweighted shortest-path
algorithm Only the class methods that are needed to write a main
routine are provided. Vertex class is shown below
![Page 39: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/39.jpg)
39
![Page 40: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/40.jpg)
40
![Page 41: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/41.jpg)
41
![Page 42: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/42.jpg)
42
![Page 43: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/43.jpg)
43
![Page 44: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/44.jpg)
44
![Page 45: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/45.jpg)
45
Example :Shortest Path Calculation
What about the version without using STL ?
![Page 46: DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.](https://reader030.fdocuments.in/reader030/viewer/2022033104/56649eab5503460f94bb031a/html5/thumbnails/46.jpg)
46
Version without using the STL Requires more work We need to use a hash table class
instead of a map Hash table will store MapEntry
objects consisting of the vertex name and Vertex it maps to
Hash table will use the vertex name as the key