Presentation is loading. Please wait.

Presentation is loading. Please wait.

DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.

Similar presentations


Presentation on theme: "DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI."— Presentation transcript:

1 DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI

2 2 ROAD MAP The Standart Template Library (STL) Introduction Basic STL Concepts Unordered Sequences : vector and list Sets Maps Examples

3 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

4 4 Basic STL Concepts Header files and using Directive Containers iterator Pairs Function Objects

5 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

6 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

7 7 A simple example #include using namespace std; int main() { cout > endl; return 0; }

8 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

9 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

10 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.

11 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

12 12 iterator Each container defines several iterators A list defines list ::iterator and list ::const_iterator The const_iterator must be used if container is nonmodifiable Example // print the contents of a Container C template void printCollection( const Container & C ) { Container :: const_iterator itr; for ( itr = c.begin () ; itr != C.end () ; itr ++ ) cout << *itr << ‘\n’; }

13 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 following template class Pair { public : Object1 first; Obejct2 second; }

14 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

15 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 & array ){ sort (array.begin(), array.end(), Comp() ); }

16 16 ROAD MAP The Standart Template Library (STL) Introduction Basic STL Concepts Unordered Sequences : vector and list Sets Maps Examples

17 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

18 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

19 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

20 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

21 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

22 22 Example /* A program that reads integers from the standard inputs and outputs them in sorted order */ #include using namespace std; int main( ) { vector 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; }

23 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

24 24 // Queue class implemented using the STL list #include using namespace std; template class Queue { public: bool isEmpty( ) const; const Object & getFront( ) const; void makeEmpty( ); Object dequeue( ); void enqueue( const Object & x ); private: list theList; };

25 25 // Queue class implemented using the STL list template bool Queue ::isEmpty( ) const { return theList.empty( ); } template const Object & Queue ::getFront( ) const { if( isEmpty( ) ) throw Underflow( ); return theList.front( ); } template void Queue ::makeEmpty( ) { while( !isEmpty( ) ) dequeue( ); } template Object Queue ::dequeue( ) { Object frontItem = getFront( ); theList.pop_front( ); return frontItem; } template void Queue ::enqueue( const Object & x ) { theList.push_back( x ); }

26 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

27 27 Set operations pair 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 )

28 28 // illustration of set, using reverse order #include using namespace std; int main( ) { set > s; // Use reverse order s.insert( "joe" ); s.insert( "bob" ); printCollection( s ); return 0; } Example

29 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

30 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 object Find requires only a key, the iterator it returns references a pair

31 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

32 32 Maps Illustration of the map : Tim’s value is 5; Bob’s value is 0

33 33 ROAD MAP The Standart Template Library (STL) Introduction Basic STL Concepts Unordered Sequences : vector and list Sets Maps Examples

34 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

35 35 Example : Generating a Concordance

36 36 Example : Generating a Concordance What about the version without using STL ?

37 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

38 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

39 39

40 40

41 41

42 42

43 43

44 44

45 45 Example : Shortest Path Calculation What about the version without using STL ?

46 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


Download ppt "DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI."

Similar presentations


Ads by Google