470 likes | 603 Views
DATA STRUCTURES AND ALGORITHMS. Lecture Notes 12 Prepared by İnanç TAHRALI. ROAD MAP. The Standart Template Library (STL) Introduction Basic STL Concepts Unordered Sequences : vector and list Sets Maps Examples. Introduction to STL. STL is a part of C++ library
E N D
DATA STRUCTURES ANDALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI
ROAD MAP • The Standart Template Library (STL) • Introduction • Basic STL Concepts • Unordered Sequences : vector and list • Sets • Maps • Examples
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
Basic STL Concepts • Header files and using Directive • Containers • iterator • Pairs • Function Objects
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
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
A simple example #include <iostream> using namespace std; int main() { cout << “First program” >> endl; return 0; }
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
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
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.
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
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’; }
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 following template <class Object1, class Object2> class Pair { public : Object1 first; Obejct2 second; }
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
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() ); }
ROAD MAP • The Standart Template Library (STL) • Introduction • Basic STL Concepts • Unordered Sequences : vector and list • Sets • Maps • Examples
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
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
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
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
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
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; }
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
// 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; };
// 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 );}
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
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 )
Example // 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; }
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
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
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
Maps Illustration of the map : Tim’s value is 5; Bob’s value is 0
ROAD MAP • The Standart Template Library (STL) • Introduction • Basic STL Concepts • Unordered Sequences : vector and list • Sets • Maps • Examples
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
Example :Generating a Concordance • What about the version without using STL ?
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
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
Example :Shortest Path Calculation • What about the version without using STL ?
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