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

Slides:



Advertisements
Similar presentations
M The University Of Michigan Andrew M. Morgan EECS Lecture 22 Savitch Ch. 16 Intro To Standard Template Library STL Container Classes STL Iterators.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
Data Structures Using C++ 2E
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.
. The Standard C++ Library. 2 Main Ideas Purpose Flexibility Efficiency Simple & Uniform Interface.
Lecture 20 “Standard” Template Library. What is the Standard Template Library? A collection of C++ classes (templates) containers vectors lists stacks.
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.
. STL: C++ Standard Library (continued). STL Iterators u Iterators are allow to traverse sequences u Methods  operator*  operator->  operator++, and.
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
CSE 332: C++ Associative Containers II Associative Containers’ Associated Types Associative containers declare additional types –A key_type gives the type.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Spring 2010 Advanced Programming Section 1-STL Computer Engineering Department Faculty of Engineering Cairo University Advanced Programming Spring 2010.
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
DATA STRUCTURES AND ALGORITHMS Lecture Notes 12 Prepared by İnanç TAHRALI.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
STL-Associative Containers. Associative Containers Sequence containers : "This is item 0, this is item 1, this is item 2…“ Associative containers : –
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.
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:
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.
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.
1 Iterators Good reference site:
Chapter 22 STL Containers §22.1 STL Basics §22.2 STL Iterators §22.3 Sequence Containers §22.4 Associative Containers §22.5 Container Adapters.
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.
STL – Standard Template Library L. Grewe. 2 Goals Lots of important algorithms, data structures in CS using Templates. is a software library partially.
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.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Learning Objective  Standard Template Library.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
Introduction The STL is a complex piece of software engineering that uses some of C++'s most sophisticated features STL provides an incredible amount.
Associative Containers Sets Maps Section 4.8. Associative Containers.
More STL Container Classes ECE Last Time Templates –Functions –Classes template void swap_val (VariableType &a, VariableType &b) { VariableType.
Programming in C++ Michal Brabec Petr Malý. Standard Template Library Containers - vector, map, set, deque, list Algorithms - copy, replace, sort, find.
Chapter 17 – Templates. Function Templates u Express general form for a function u Example: template for adding two numbers Lesson 17.1 template Type.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Object-Oriented Programming (OOP) Lecture No. 42.
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.
Object-Oriented Programming (OOP) Lecture No. 41
CS212: Object Oriented Analysis and Design
Concepts of Programming Languages
Regarding homework 9 Many low grades
Programming with ANSI C ++
Standard Template Library (STL)
Chapter 22: Standard Template Library (STL)
Today’s Learning Objective
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 Iterators Separating Container from Data Access.
Iterators and STL Containers
Standard Template Library (STL)
STL and Example.
An Introduction to STL.
Some Definitions vector, string, deque, and list are standard sequence containers. set, multiset, map, multimap, unordered_set, unordered_multiset, unordered_map.
Recitation Outline Hash tables in C++ STL Examples Recursive example
14 – Sequential Containers
A dictionary lookup mechanism
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 u 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 (skips one element in the vector) 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

Iterator Validity u Third try… Container C; C::iterator i; for(i = C.begin(); i != C.end(); i++ ) if( f( *i ) ) // some test i= C.erase(i); // erase returns the iterator for the next element in the container. Still does not work for vector.

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 (what is value_type of map) ? Recall  map keeps pairs  KeyType key – “key” of entry  DataType 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 data_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, set_difference, set_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

Ex8: Huffman Code u Very easy !! u Compression of text files, implement using STL: u Priority queue u Map u Vector/deque u Function objects u Copy (algorithm) u The more STL you’ll use the more you’ll learn.