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

Slides:



Advertisements
Similar presentations
Hold data and provide access to it. Random-access containers: -Allow accessing any element by index -arrays, vectors Sequential containers: -Allow accessing.
Advertisements

Chapter 6 Queues and Deques.
SEG4110 – Advanced Software Design and Reengineering TOPIC J C++ Standard Template Library.
1 STL Map & Multimap Ford & Topp Chapter 11 Josuttis Sections: 6.5 & 6.6 CSE Lecture 15 – Maps.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
Beginning C++ Through Game Programming, Second Edition
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
More on the STL vector list stack queue priority_queue.
OOP Etgar 2008 – Recitation 101 Object Oriented Programming Etgar 2008 Recitation 10.
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
CMSC 202 Lesson 24 Iterators and STL Containers. Warmup Write the class definition for the templated Bag class – A bag has: Random insertion Random removal.
1 Lecture 8: Introduction to C++ Templates and Exceptions  C++ Function Templates  C++ Class Templates.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Data Structures Using C++ 2E
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Containers Overview and Class Vector
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
Introduction to STL and the vector container class CS342 Data Structures Based on Ford & Topp.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 4 Prepared by İnanç TAHRALI.
Generic Programming Using the C++ Standard Template Library.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Chapter 16 Stacks & Queues. Objective In this chapter we will learn:  Stacks  Queues  Different implementations (arrays and linked list) of both 
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan and A. Ranade.
Templates code reuse - inheritance - template classes template classes - a class that is not data-type specific - eg. a class of Array of any type - intArray,
1. The term STL stands for ? a) Simple Template Library b) Static Template Library c) Single Type Based Library d) Standard Template Library Answer : d.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Introduction to the Standard Template Library (STL) A container class holds a number of similar objects. Examples: –Vector –List –Stack –Queue –Set –Map.
Iterator for linked-list traversal, Template & STL COMP171 Fall 2005.
Lecture 11 Standard Template Library Lists Iterators Sets Maps.
1 Joe Meehean.  List of names  Set of names  Map names as keys phone #’s as values Phil Bill Will Phil Bill Will Phil Bill Will Phil: Bill:
Copyright 2006, The Ohio State University Introduction to C++ Templates l C++ Function Templates l C++ Class Templates.
Lecture 7 : Intro. to STL (Standard Template Library)
Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.
A gentle introduction to the standard template library (STL) Some references:
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class.
1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
More STL Container Classes ECE Last Time Templates –Functions –Classes template void swap_val (VariableType &a, VariableType &b) { VariableType.
CS212: Object Oriented Analysis and Design Lecture 26: STL Containers.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Main Index Contents 11 Main Index Contents Sets Defined by a key along with other data Sets Defined by a key along with other data Key-Value Data Key-Value.
1 The Standard Template Library The STL is a collection of Container classes These are class templates for containers. A container is an object that stores.
List Structures What is a list? A homogeneous collection of elements with a linear relationship between the elements linear relationship - each element.
CS212: Object Oriented Analysis and Design
Cpt S 122 – Data Structures Abstract Data Types
Standard Template Library (STL)
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Collections Intro What is the STL? Templates, collections, & iterators
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Associative Structures
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Recursive Linked List Operations
Lists - I The List ADT.
Lists - I The List ADT.
Lecture 8 : Intro. to STL (Standard Template Library)
Standard Template Library
Collections Intro What is the STL? Templates, collections, & iterators
Standard Template Library
An Introduction to STL.
Chapter 3 Lists, Stacks, and Queues
A dictionary lookup mechanism
Standard Template Library
Presentation transcript:

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

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

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 Basic STL Concepts Header files and using Directive Containers iterator Pairs Function Objects

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 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 A simple example #include using namespace std; int main() { cout > endl; return 0; }

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 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 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 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 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 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 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 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 ROAD MAP The Standart Template Library (STL) Introduction Basic STL Concepts Unordered Sequences : vector and list Sets Maps Examples

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 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 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 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 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 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 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 // 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 // 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 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 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 // 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 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 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 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 Maps Illustration of the map : Tim’s value is 5; Bob’s value is 0

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

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 Example : Generating a Concordance

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

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

40

41

42

43

44

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

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