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)

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 19 Standard Template Library. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Iterators Constant and mutable.
Introduction to C Programming
Chapter6 LISTS AND STRINGS. Outline 1. List Specifications 2. List Implementations (a) Class Templates (b) Contiguous (c) Simply Linked (d) Simply Linked.
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)
CSE 332: C++ Algorithms I The C++ Algorithm Libraries A standard collection of generic algorithms –Applicable to various types and containers E.g., sorting.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Lecture 3 Feb 4 summary of last week’s topics and review questions (handout) Today’s goals: Chapter 1 overview (sections 1.4 to 1.6) c++ classes constructors,
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
C++ for Engineers and Scientists Third Edition
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 16 Exceptions,
Basic C++ Sequential Container Features
Rossella Lau Lecture 12, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 12: An Introduction to the STL  Basic.
CSE 332: C++ program structure and development environment C++ Program Structure (and tools) Today we’ll talk generally about C++ development (plus a few.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
CSE 332: Combining STL features Combining STL Features STL has containers, iterators, algorithms, and functors –With several to many different varieties.
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers ( int ) vs. intervals ( pair )
CSE 332: C++ Algorithms II From Last Time: Search with Generic Iterators Third generalization: separate iterator type parameter We arrive at the find algorithm.
Writing Your Own STL Container Ray Lischner
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Data Structures Using C++ 2E
CSE 425: Data Types II Survey of Common Types I Records –E.g., structs in C++ –If elements are named, a record is projected into its fields (e.g., via.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
CNS  Sequences  vector,deque,list,(string),forward_list  Container Adapters  queue, stack, priority_queue  Associative Containers  set, unordered_set.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved.
CSE 332: C++ Type Programming: Associated Types, Typedefs and Traits A General Look at Type Programming in C++ Associated types (the idea) –Let you associate.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
CSE 332: C++ STL algorithms C++ STL Algorithms Generic algorithms –Apply to a wide range of types E.g., sorting integers (long) or intervals (long, long)‏
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Standard Template Library (STL)
Targil 6 Notes This week: –Linear time Sort – continue: Radix Sort Some Cormen Questions –Sparse Matrix representation & usage. Bucket sort Counting sort.
Pointers OVERVIEW.
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.
CSC 211 Data Structures Lecture 13
CSE 332: C++ STL containers Review: C++ Standard Template Library (STL) The STL is a collection of related software elements –Containers Data structures:
CSE 332: C++ execution control statements Overview of C++ Execution Control Expressions vs. statements Arithmetic operators and expressions * / % + - Relational.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
1 Iterators Good reference site:
CSE 332: C++ template examples Concepts and Models Templates impose requirements on type parameters –Types that are plugged in must meet those requirements.
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.
Writing Generic Functions Lecture 20 Hartmut Kaiser
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Overview of C++ Templates
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
STL CSSE 250 Susan Reeder. What is the STL? Standard Template Library Standard C++ Library is an extensible framework which contains components for Language.
CSE 332: C++ template examples Today: Using Class and Function Templates Two examples –Function template for printing different types –Class template for.
Arrays. Topics to be Covered... Arrays ◦ Declaration ◦ Assigning values ◦ Array manipulation using loops Multi-dimensional arrays ◦ 2D arrays ◦ Declaration.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Chapter 8 Writing Generic Functions. Objectives Understand the use of generic functions. Learn about the use of templates, their advantages and pitfalls.
Programming Fundamentals. Today’s Lecture Array Fundamentals Arrays as Class Member Data Arrays of Objects C-Strings The Standard C++ string Class.
CSE 332: C++ templates and generic programming II Review: Concepts and Models Templates impose requirements on type parameters –Types that are plugged.
Software Design 2.1 STL concepts l Container: stores objects, supports iteration over the objects  Containers may be accessible in different orders 
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.
Introduction to Programming Lecture 12. Today’s Lecture Includes Strings ( character arrays ) Strings ( character arrays ) Algorithms using arrays Algorithms.
Motivation for Generic Programming in C++
CS212: Object Oriented Analysis and Design
Programming with ANSI C ++
Motivation and Overview
Standard Template Library (STL)
7 Arrays.
CS212: Object Oriented Analysis and Design
Engineering Problem Solving with C++ An Object Based Approach
Presentation transcript:

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) –Give access the current element to which it points An iterator may be able to do 2 other important things –Move to point to the next element in a range –Be tested for having run through the entire range Intent (based on Gamma et al., “Design Patterns”) –Provide a way to access elements of a container sequentially without exposing its underlying representation Iterators help provides polymorphism –Same interface, but different iterator implementations –Underlying containers give different behaviors We’ll consider iterator interface methods above with –istream, ostream, array, linked list, bi-linked list

CSE 332: C++ STL iterators Overview of STL Iterators STL iterators generalize different uses of pointers Interface between algorithms and data structures –Algorithm manipulates iterators, not containers Iterator “value” can be in one of 3 kinds of states: –Dereferenceable (points to a valid location, like in an array) –Past the end (points just past last valid location) –Singular (points to nothing, like a zero pointer) Iterators may be compared for equality Iterators may be copied and assigned The iterator family consists of five concepts: –Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator –We’ll look at each of these categories in detail

CSE 332: C++ STL iterators STL Iterator Syntax and Semantics Pointers and integers are iterators for (int * p = &A[0]; p – A < MAX; ++p) { cout << *p << endl; } Pointers (not integers) are also STL iterators –Relies on associated types tricks we’ll cover later –Uses traits based on typedef/struct/specialization The compiler can only check the syntax Iterator definition must provide good semantics –Including memory, aliasing, time complexity –Is it ok to implement p+= as a for loop?

CSE 332: C++ STL iterators Linear Search Example char* strchr(char* s, int c) –From Austern “Generic Programming and the STL” –Sequential (linear) search for the first instance of character c in C-style string s Not a very general solution –Only handles char (not wchar_t, uchar, etc.) –“ Range ” is always defined from start to ‘\0’ A “ null terminated ” or “ zero terminated ” string in C/C++ First generalization: use a proper range –Provide an integer range length (how far to count) –Provide a first and last pointer into the array char* findl(char* start, char* end, int c)

CSE 332: C++ STL iterators Introduction to Ranges char* findl(char* start, char* end, int c); searches all positions in the string (from start up to but not including end ) for a position with value c –A closed/open range: [start, end) A few questions about ranges to consider – At what position is ‘\0’ in “hello” ? –What is the last element in [0,1) ? Closed/open ranges help avoid off-by-one errors –The number of elements in the range [start, end) is end - start

CSE 332: C++ STL iterators Some Definitions Related to Ranges A valid range can be traversed safely with an iterator An empty range [p,p) is valid If [first, last) is valid and non-empty, then [first+1, last) is also valid –Proof: iterative induction on the range If [first, last) is valid –and position mid is reachable from first –and last is reachable from mid –then [first, mid) and [mid, last) are also valid If [first, mid) and [mid, last) are valid, then [first, last) is valid –Proof: divide and conquer induction on range

CSE 332: C++ STL iterators Iterator Concept Hierarchy Input IteratorOutput Iterator Forward Iterator Bidirectional Iterator Random Access Iterator value persists after read/write values have locations can express distance between two iterators read or write a value (one-shot) Linked-list style access ( slist ) Bi-linked-list style access ( list ) Array/buffer style access ( vector, deque ) “destructive” read at head of stream ( istream ) “transient” write to stream (ostream)

CSE 332: C++ STL iterators Input/Output Iterator Concepts & Models Important Input Iterator Concept Expressions *i (read value at the head of the stream) i->m (access member through iterator) ++i, i++ (move the iterator to next element in stream) Some Models of the Input Iterator Concept istream_iterator, most other STL iterators Important Output Iterator Concept Expressions X y(x), X y=x, y = x (copy construct / assign iterators) *x = t, (write value t into the stream) x++, ++x (move the iterator to next element in stream) Some Models of Output Iterator Concept front_insert_iterator back_insert_iterator ostream_iterator

CSE 332: C++ STL iterators Forward/Bidirectional Iterator Concepts & Models Important Forward Iterator Concept Expressions –Can pass same forward iterator in multiple arguments X x, X(),(default construction) ++i, i++ (move from location to location) *i (non-destructive access to container element) Some Models of the Forward Iterator Concept slist ::const_iterator hash_set ::iterator Important Bidireational Iterator Concept Expressions --i, i-- (move from location back to earlier location) Some Models of the Bidirectional Iterator Concept list ::iterator, set ::iterator

CSE 332: C++ STL iterators Random Access Iterator Concepts & Models Important Random Access Iterator Concept Expressions i+=n, i-=n (moving iterator given distance in constant time) i+n, n+i, i-n, n-i, i-j, i<j (iterator arithmetic) i[n], i[n]=t (indexing a container using an iterator) –Thought Question: we can express the distance between two Forward Iterators, so why don’t those iterators have i-j or i<j ? Some Models of the Random Access Iterator Concept vector ::iterator deque ::iterator char *

CSE 332: C++ STL iterators Associated Types: Key Ideas to Consider Difference Type –Type for “distance” between two iterators i1 and i2 –E.g., ptrdiff_t Reference, Value Types –For T *p, value type is T, *p normally returns T & –For const T *p, value type is const T, *p gives const T & Iterator Category –What concept(s) it models how far? units?

CSE 332: C++ STL iterators Advice for Designing Your Own Iterators Use the iterator concept requirements as a checklist Make you support both constant and mutable objects Define associated types appropriately –More on this in the lecture on generic programming Provide as wide an iterator interface as possible without loss of efficiency Obey the aliasing rule we talked about with pointers –Two iterators equal if and only if they point to same variable i == j &(*i) == &(*j) *i == *j

CSE 332: C++ STL iterators Advice for Using Iterators Write a concept expression checklist for iterator developers to use in designing their iterators Watch out for empty ranges Require as narrow an iterator interface as possible without loss of efficiency –Avoid over-constraining unnecessarily –E.g., requiring just == and and != Use selective dispatching techniques to provide both efficiency and generality

CSE 332: C++ STL iterators Example of Using Iterators in the STL From Austern, pp. 355 Copies values from an istream into a vector What exactly is going on here? int main () { vector V; copy (istream_iterator (cin), istream_iterator (), back_inserter (V)); } (Thanks to Morgan Deters for this example)

CSE 332: C++ STL iterators How the Iterator Works in this Example From the g STL source code : template class istream_iterator {... public: istream_iterator() : _M_stream(&cin), _M_end_marker(false) {} istream_iterator(istream& __s) : _M_stream(&__s) { _M_read(); }... };

CSE 332: C++ STL iterators For Next Time Topic: C++ STL Algorithms Assigned Reading –pages pages