Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes.

Slides:



Advertisements
Similar presentations
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Advertisements

C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
CS 307 Fundamentals of Computer Science 1 Abstract Data Types many slides taken from Mike Scott, UT Austin.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Chapter 12 C Data Structures Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 12 – Data Structures Outline 12.1Introduction.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
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.
Important Problem Types and Fundamental Data Structures
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Copyright © Wondershare Software Introduction to Data Structures Prepared by: Eng. Ahmed & Mohamed Taha.
Writing Your Own STL Container Ray Lischner
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Chapter 12 Data Structure Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
1 Hash Tables  a hash table is an array of size Tsize  has index positions 0.. Tsize-1  two types of hash tables  open hash table  array element type.
DATA STRUCTURES ACM EXECUTIVE BODY 2k11.  A series of elements of same type  Placed in contiguous memory locations  Can be individually referenced.
Data Structures Using C++ 2E
Chapter 3 List Stacks and Queues. Data Structures Data structure is a representation of data and the operations allowed on that data. Data structure is.
Containers Overview and Class Vector
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
111 © 2002, Cisco Systems, Inc. All rights reserved.
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)
C++ STL CSCI 3110.
Software Design 1.1 Tapestry classes -> STL l What’s the difference between tvector and vector  Safety and the kitchen sink What happens with t[21] on.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 22: Standard Template Library (STL)
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
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,
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.
1 Finding Shortest Paths with A* Search A* search operates similarly to Dijkstra’s algorithm, but extends the cost function to include an estimated distance.
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.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
The ADT Table The ADT table, or dictionary Uses a search key to identify its items Its items are records that contain several pieces of data 2 Figure.
Lecture 7 : Intro. to STL (Standard Template Library)
Data Structures Chapter 6. Data Structure A data structure is a representation of data and the operations allowed on that data. Examples: 1.Array 2.Record.
Data Structures for Midterm 2. C++ Data Structure Runtimes.
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
The Standard Template Library Container Classes Version 1.0.
STL Containers Inside Peter Sikachev Institute of Computer Graphics and Algorithms Vienna University of Technology.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
C++ Review STL CONTAINERS.
CSCI 383 Object-Oriented Programming & Design Lecture 25 Martin van Bommel.
STL Associative Containers navigating by key. Pair Class aggregates values of two, possibly different, types used in associative containers defined in.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Unit VI.  C++ templates are a powerful mechanism for code reuse, as they enable the programmer to write code (classes as well as functions) that behaves.
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.
Final Exam Review COP4530.
Object-Oriented Programming (OOP) Lecture No. 41
Cpt S 122 – Data Structures Abstract Data Types
Data Structure By Amee Trivedi.
Chapter 12 – Data Structures
Standard Template Library (STL)
ENERGY 211 / CME 211 Lecture 19 November 3, 2008.
Prof. Michael Neary Lecture 7: The STL Prof. Michael Neary
structures and their relationships." - Linus Torvalds
structures and their relationships." - Linus Torvalds
Final Exam Review COP4530.
Standard Template Library
Important Problem Types and Fundamental Data Structures
Standard Template Library
structures and their relationships." - Linus Torvalds
Standard Template Library
Presentation transcript:

Computer Science and Software Engineering University of Wisconsin - Platteville 11.Standard Template Library Yan Shi CS/SE 2630 Lecture Notes

What is STL?  The Standard Template Library (STL) is a subset of ISO/ANSI C++ standard library.  It provides 3 kinds of facilities: —containers —iterators —generic algorithms Appendix E in the textbook Visual Studio Help Doc:

STL Container  Sequence containers: maintain the original ordering of inserted elements —list, vector, deque  Associative containers: elements are inserted in a pre-defined order —map, set, …  Container adapters: simple variations of the sequence containers —queue, stack, priority_queue —they do NOT support iterators: cannot be used by STL algorithms!  Container classes are template classes —e.g. list, stack

STL Iterators  STL iterators enable cycling through a container, one item at a time —allow C++ programs to access items in a container without knowing the internal structure of the container —each STL container class defines one or more iterator types:  list ::iterator iter; —similar as GetNext() operation —it simply represents the location of an item within the container —a generalization of a pointer  *iter // item referred to by iter  iter++ // move to the next item

Types of Iterators  Input iterators: —can only step forward; permit only fetching; used for istream  Output iterators: —can only step forward; permit only storing; used for ostream  Forward iterators: —permit both fetching and storing  Bidirectional iterators —can move both forward and backward  Random access iterators —allow direct (random) access to any item in a container Random access > Bidirectional > Forward > Input/Output  Behavior defines iterator: —anything that acts like an iterator is an iterator! —e.g., pointers to an array is an iterator.

Iterator Operations OperationsInputOutputForwardBidirecti onal Random Access *rYYYY r++; ++rYYYYY r--; --rYY r == r2; r != r2YYYYY *r = valueYYYY r[i]Y r += i; r -= i;Y r + i; r – i;Y r – r2 //# of itemsY r r2Y r = r2Y

Iterator Operations OperationsInputOutputForwardBidirecti onal Random Access *rYYYY r++; ++rYYYYY r--; --rYY r == r2; r != r2YYYY *r = valueYYYY r[i]Y r += i; r -= i;Y r + i; r – i;Y r – r2 //# of itemsY r r2Y r = r2Y

STL Algorithms  An STL algorithm is a template function that has iterators for its parameter types. —generic because it is a template and works with iterators, not containers vector v; int myArray[100]; … sort( v.begin(), v.end() ); sort( &myArray[0], &myArray[100] ); sort( myArray, myArray+100 ); // why 100? sort algorithm: template void sort ( RandomAccessIterator first, RandomAccessIterator last); —The range used is [first, last)

Vector Class  Generalize the concept of an array —index: 0 to #elements – 1 —but growable! —implemented with a dynamic array —has random access iterator #include using namesapce std; vector nums(100); // array of 100 integers, initialized to 0  Operations: — operator[] does not do bound checking — at(index) access item; throws out_of_range exception — operator== returns true if two vectors are the same — size() # of elements in the vector — push_back(item) adds item to the end of the vector — pop_back() deletes the element at the end of the vector — front() returns a reference to the first element in the vector — back() returns a reference to the last element in the vector

Vector Class  Be aware: Modifying a container while iterating over it can "invalidate" the iterator!  erase(iterator) : removes item at iterator position  insert(iterator, item) : insert item before iterator  Both erase and insert invalidate all iterators beyond the insert/erase point —they result in reallocating the array

Vector Class  The following discussion is true in general to all containers:  a vector pointer? —need to delete the pointer if pointing at dynamically allocated vector object  a vector of pointers? —need to manually delete all dynamically allocated objects those pointers are pointing at before the vector goes out of scope  const_iterator: —for iterators over a collection that cannot be changed vector ::const_iterator iter; … (*iter).Print(); // it has to be a const function! // or // iter->Print();

Function Objects  Apply an operation to each of the elements in the range of a container template Function for_each (InputIterator first, InputIterator last, Function fn);  Sort a range of element in a container in descending order: template void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);  Function object or functor: a class object that acts like a function which overloads the function call operator. class Double { public: int operator() ( int i ) { return 2*i; } };... Double f; int n = f(15); // n becomes 30

list Class  template for a doubly linked list —has bidirectional iterator —cheap insertion/deletion, O(i) to access item i  Inserting into a list while iterating over it is safe.  If iter is an iterator, executing erase(iter) invalidates iter (and any iterator equal to iter )  Erasing other positions is fine; —if xs is a list: iterator y = x; x++; xs.erase(y); invalidates y but not x  The list member functions merge, reverse, unique, remove, and remove_if have been optimized.mergereverseuniqueremoveremove_if

deque Class  double-ended queue: “First or Last In, First or Last Out”  very similar as a vector: —provides fast random access into sequences of varying length.  Differences from a vector: —provide fast insertion and deletion at both ends of the collection – O(1)  by providing unused reserve on both ends  vector is fast only at the back —Memory allocation is not guaranteed to be contiguous.  accessing items in a deque tends to be slower than in a vector  accessing elements in a deque by offsetting a pointer to another element causes undefined behavior. —Any insertion or deletion other than the ends invalidates all iterators to the deque.  How about the ends? check msdn for details.  When to use deque? —people wait in line. front gets served, end loses patience and leaves.

stack Adaptor  An adaptor does NOT directly implement the structure; instead, it provides a new interface for an existing container.  By default, stack “adapts” deque : LIFO  #include  Operations: —empty, pop, push, size, top —comparison (, =, ==, != ): lexicographical  the first pair of element that are unequal determines the comparison result

queue Adaptor  By default, queue “adapts” deque : FIFO  #include  Operations: —empty, back, front, pop, push, size —comparison(, =, ==, != )

priority_queue Adapter  #include  similar with queue: —push() means enqueue —pop() means dequeue  different from queue: —reordering right after enqueue to ensure the “highest priority” item is always at the front of the queue.  Operations —empty, pop, push, size, top  Example: —job queue on a Linux server

Priority Queue Implementation  Unsorted list —enqueue: insert at the end of the list O(1) —dequeue: search and fetch the highest priority item O(n)  Array based sorted list —enqueue: insert and keep the order O(n) —dequeue: fetch the last item O(1)  Sorted linked list —enqueue: insert and keep the order O(n) —dequeue: fetch the first item O(1)  Binary search tree —enqueue: insert and keep the order O(log 2 n) —dequeue: fetch the last item O(log 2 n)

string Class  string is not part of STL, but is part of the standard library.  need to #include  besides the operations we have learned, string has many other operations similar to STL containers: —begin, end, clear, front, back, at, insert, erase, push_back, pop_back,...

Associative Containers  The associative containers can be grouped into two subsets: maps and sets.  Map, aka dictionary, consists of a key/value pair: —key: used to order the sequence —value: associated with that key — map, multimap (allow multiple keys ) —not officially part of STL: hash_map, hash_multimap store elements as a hash table to improve search time  Set: an ascending container of unique elements — set, multiset (allow multiple instances of an element) —not officially part of STL: hash_set, hash_multiset

set Class  an ascending container of unique elements —< must be defined —O(log 2 n) insertion, deletion —bidirectional iterator —implemented based on balanced binary search tree (like a red-black tree): sorted —the only thing that invalidates an iterator is an erase on that iterator: similar as list  Operations: —size, empty, begin, end, find, lower_bound, upper_bound —insert, erase

Red-Black Tree  A type of self-balancing binary search tree  Rules for red-black trees (Data Structres and the STandard Template Library, William J. Collins, McGraw-Hill, 2003) —all nodes are colored red or black —if an item is red, its parent must be black —the number of black items must be the same in all paths from the root item to an item with no children or with one child  Maximum height is less than 2 log 2 n  a red-black tree demo a red-black tree demo

multiset Class  used when more than one instances of an element is possible —The value serves as the key — erase ( key_value ) : returns the number of elements erased — equal_range : returns a pair of iterator

map Class  Each element is a pair of key and value. —Sorted: key is unique and used to sort the data. —Use bidirectional iterator. —implemented as balanced binary search tree —the only thing that invalidates an iterator is an erase on that iterator: similar as list  Operation —begin, end, find, at, count, equal_range —insert, erase  multimap is used when the key is not necessarily unique.

Choosing Containers  The choice of container type should be based in general on the type of searching and inserting required by the application. —Use vector to manage a sequence if:  random access to any element is at a premium  insertions or deletions of elements are only required at the end of a sequence. —Use deque if you want to use vector but also need to do insertion/deletion at the front of a sequence. —Use list if need to do merge, reverse, unique, remove, and remove_if —Associative containers are optimized for the operations of lookup, insertion and removal.  O(log 2 N) insertion/deletion.  Insertion doesn’t invalidate iterators; deletion only invalidates iterators pointing to the elements to delete.