. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.

Slides:



Advertisements
Similar presentations
Data Structures Using C++ 2E
Advertisements

. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
C++ Templates. What is a template? Templates are type-generic versions of functions and/or classes Template functions and template classes can be used.
C++ Sets and Multisets Set containers automatically sort their elements automatically. Multisets allow duplication of elements whereas sets do not. Usually,
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
What is generic programming? The essence of the generic programming approach is concept development: systematic classification of computing components.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Concept= a set of abstractions (e.g., types) (Generic Programming) Programming with Concepts defined by a set of requirements {vector, deque, list, set,
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 22: Standard Template Library (STL)
Data Structures Using C++1 Chapter 13 Standard Template Library (STL) II.
. STL: C++ Standard Library. Main Ideas u General purpose: generic data structures & algorithms, templates u Flexibility: Allows for many combinations.
Generic programming starts with algorithms. Lift Minimal requirements: works with maximal family of types Concrete algorithm: requires specific data type.
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.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
Standard Template Library There are 3 key components in the STL –Containers –Iterators –Algorithms Promote reuse More debugged May be more efficient.
Data Structures Using C++ 2E
Containers Overview and Class Vector
Containers and Iterators CNS 3370 Copyright 2003, Fresh Sources, Inc.
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.
SNU OOPSLA Lab. Chap17. Standard Containers © copyright 2001 SNU OOPSLA Lab.
PRESENTED BY: RAJKRISHNADEEPAK.VUYYURU SWAMYCHANDAN.DONDAPATI VINESHKUMARREDDY.LANKA RAJSEKHARTIRUMALA KANDURI ALAN.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Overview 18.1 Iterators 18.2 Containers 18.3 Generic Algorithms Slide
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)
Data Structures Using C++ 2E Chapter 13 Standard Template Library (STL) II.
Review for Final Andy Wang Data Structures, Algorithms, and Generic Programming.
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.
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
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:
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Data Structures Using C++1 Chapter 4 Standard Template Library (STL)
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
CS 403, Class 23Slide #1 CS Programming Languages Class 23 November 16, 2000.
 2003 Prentice Hall, Inc. All rights reserved.m ECE 2552 Dr. Këpuska based on Dr. S. Kozaitis Summer Chapter 15 - Class string and String Stream.
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.
CS 403: Programming Languages Lecture 24 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Intro to the C++ STL Timmie Smith September 6, 2001.
1 Associative Containers Ordered Ordered Unordered UnorderedSets Maps as sets of pairs Set API Ex: Sieve of Eratosthenes Ex: Sieve of EratosthenesImplementation.
The Standard Template Library Container Classes Version 1.0.
Standard Template Library (STL) - Use Vector and Deque
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.
Associative Containers Sets Maps Section 4.8. Associative Containers.
CSE 332: C++ STL iterators What is an Iterator? An iterator must be able to do 2 main things –Point to the start of a range of elements (in a container)
Properties: -The value in each node is greater than all values in the node’s subtrees -Complete tree! (fills up from left to right) Max Heap.
Algorithms CNS 3370 Copyright 2003, Fresh Sources, Inc.
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.
Regarding homework 9 Many low grades
Standard Template Library (STL)
What remains Topics Assignments Final exam
Programming with Concepts
Chapter 22: Standard Template Library (STL)
Trees 1: Theory, Models, Generic Heap Algorithms, Priority Queues
CS212: Object Oriented Analysis and Design
Generic Programming Karl Lieberherr 12/1/2018 Generic Programming.
Elements are always copied when they are put into a container
STL Библиотека стандартных шаблонов
Standard Template Library
Standard Template Library
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Standard Template Library
Presentation transcript:

. STL: C++ Standard Library (continued)

STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and operator— u Different types of iterators - to support read, write and random access u Containers define their own iterator types u Changing the container can invalidate the iterator

Iterator Types u Output: write only and can write only once u Input: read many times each item u Forward: supports both read and write u Bi-directional: supports also decrement u Random: supports random access (just like C pointer)

Iterators & Containers Bidirectional iterators: u list, map, set Random access iterators: u vector, deque Input/output/forward iterators: u iostreams

Iterators & Containers Every STL container T provides: class T { … typedef … iterator // iterator type T iterator begin(); // first element of the container iterator end(; // element after last of the container };

Iterators & Containers Typical code will look like: Container C … Container::iterator i for( i = C.begin(); i != C.end(); i++) // do something with *i

Iterators & Containers Iterators allow to access/modify elements Container C; Container::iterator i,j;  C.insert(i,x) – insert x before i  C.insert(i,first,last) – insert elements in [first,last) before i  C.erase(i) – erase element i points to  C.erase(i,j) – erase elements in range [i,j)

Iterator validity u When working with iterators, we have to remember that their validity can change Whats wrong with this code? Container C; C::iterator i; for( i = C.begin(); i != C.end(); i++ ) if( f( *i ) ) // some test C.erase(i); // remove this element

Iterator validity Two cases: u list, set, map  i is not a legal iterator u vector  i points to the element after In either case, this is not what we want…

Iterator validity Second try… Container C; C::iterator i = C.begin(); while( i != C.end() ) { C::iterator j = i++; if( f( *j ) ) // some test C.erase(j); // remove this element } Works for set, map, list, not vector or deque

Iterators and Map Suppose we work with map dictionary; map ::iterator i; … i = dictionary.begin(); What is the type of *i ?

Iterators and Map Every STL container type Container defines Container::value_type Type of elements stored in container  This is the type returned by an iterator Container::value_type Container::iterator operator*();

Iterators and Map u Ok, so what type of elements does a map return? Recall  map keeps pairs  KeyType key – “key” of entry  ValueType value – “value” of entry

Pairs template struct pair { typedef T1 first_type; typedef T2 first_type; T1 first; T2 second; pair( const T1& x, const T2& y ) : first(x), second(y) {} };

Map value_type template< class Key, class T, class Cmp = less > class map { public: typedef pair value_type; typedef Key key_type; typedef T mapped_type; typedef Cmp key_compare; };

Using map iterator map dict; … map ::iterator i; for( i = dict.begin(); i != dict.end(); i++ ) { cout first << “ “ second << “\n”; } [See dictionary.cpp]

Iterators and Assoc. Containers Additional set of operations:  iterator C::find(key_type const& key) Return iterator to first element with key. Return end() if not found  iterator C::lower_bound(key_type const& key) Return iterator to first element greater or equal to key  iterator C::upper_bound(key_type const& key) Return iterator to first element greater than key

Iterators & Streams Can access iostreams through iterators: istream_iterator in(cin); istream_iterator endOfInput; ostream_iterator out(cout); while( in != endOfInput ) { string s = *in++; *out++ = s; *out++ = “ “; } see useStreamIterators.cpp

Inserters istream_iterator in(cin); istream_iterator endOfInput; vector vect; back_insert_iterator > back(vect); // copy input words into vector… while( in != endOfInput ) *back++ = *in++; // same as: vect.push_back(*in++)

Inserters Inserters are output iterators u back_insert_iterator ( C& c) Insert at back of c u front_insert_iterator ( C& c) Insert at front of c u insert_iterator (C& c, Iter i) Insert at just before i Allow to write into containers in generic algorithms

Do-it-yourself iterators u You can create iterators Check list:  Define the appropriate operators  Ensure copy constructor/operator  Define the right typedefs use inheritance from iterator class [See TokenIterator.h]

Sequence Adapters u Adapters of basic containers u Very easy, but limited interface stack  provides push, pop, top, size and empty queue  also provides back priority_queue u provides same interface as stack u uses a compare function object

Container summary []List opsFront opsBack opsIterators vectorconstn+const+Random listconst Bi-direct dequeconstn Random stackconst queueconst priority_queuelog(n) maplog(n)log(n)+Bi-direct setlog(n)+Bi-direct

Algorithms Overview u Sequence operations  Non modifying: for_each, find, count, search, mismatch, equal  Modifying: transform, copy, swap, replace, fill, generate, remove, unique, reverse, rotate, random_shuffle u Sorted sequences operations  sort, lower_bound, upper_bound, equal_range, binary_search, merge, includes, set_union, intersection, difference, symmetric_difference

Algorithms u Most STL algorithms works on sequences u Sequences are passed as two iterators:  beginning element  element one after last u Algorithms depend on iterator type not on container type pq sequence [p,q)

Copy template Out copy(In first, In last, Out res) { while (first != last) *res++ = *first++; return res; } See useCopy.cpp

Non-modifying Sequence Algorithms  In find(In first, In last, const T& val) find the first occurence of val in the sequence  In find_if(In first, In last, Pred p) find the first element satisfying p  I1 find_first_of(I1 f1, I2 l1, I2 f2, I2 l2) find the first match between two sequences.  I1 search( I1 f1, I1 l1, I2 f1, I2 l2 ) search for the sequence f2...l2 inside f1..l1

Sorted Sequence Algorithms  sort(In first, In last[, class cmp]) find the first occurence of val in the sequence  In lower_bound(In first, In last, T const & val[, class cmp]) find the first element not less than val  bool binary_search(In first, In last, T const & val[, class cmp]) check if val appears in the sequence  Out merge( I1 f1, I1 l1, I2 f1, I2 l2, Out out ) merge two sorted sequences and write the merged sequence onto the output iterator out

Ex4: Interactive Graph Operations u An interactive shell that allows to perform graph operations Gcalc> G1 = {x11, x22 | } Gcalc> G2 = {x11, x22 | } Gcalc> G3 = G1*G2 Gcalc> print G3

Ex5 Preview Extend the graph calculator u Weighted graphs u Algorithms: shortest path, minimum spanning tree, max flow, etc. u Load/Save file

Ex4: Components u Graph data structure u Symbol Table u Command parser u Command evaluater Emphasis: extendibility of command syntax for next exercise

Graph Data Structure Your design show allow to u Constructors/copy etc. u Add vertices/edges u Iterate over vertices u Iterate over parents of a vertex u Iterate over children of a vertex u Graph operations