This chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness.

Size: px
Start display at page:

Download "This chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness."

Transcription

1 Iterators Overview We have introduced, used, built, and studied iterators in several contexts, including List<>, TDeque<>, and TVector<>. We have seen that ordinary pointers also can be thought of as iterators for arrays. The importance of iterators for List<> was fairly obvious, from their introduction, since there is no other mechanism to access list elements. The importance of iterators for the other containers was perhaps less clear, until we encountered generic algorithms. Now we know that iterators provide a critical interface between generic algorithms and containers, thus enabling the re usability of code for both container and algorithm implementations. Iterators are perhaps the key concept making generic programming actually work. This chapter serves mainly to gather and organize information about iterators. Some new concepts are also introduced for completeness. Iterators are made so useful by giving them a uniform and predictable public interface with which algorithms may act as clients, while targeting specific containers through implementation details. For this reason, it is useful to classify iterators according to their public interface functionality, and it is also useful to prevent the number of categories from growing unmanageably large. C++ iterators may be classified into six categories according to their public interface functionality, as follows: input iterators output iterators forward iterators bidirectional iterators random access iterators adaptor iterators Of these we have so far only encountered bidirectional and random access iterators. These two categories are by far the most common. We will also introduce and use insert iterators, an example in the category of adaptor iterators, but most of the other categories we will leave for your study in the STL itself, as they pertain less to data structures and algorithms. Terminology Support Consistency of terminology is a critical feature for both containers and iterators. The mechanism used in the fsu template library is the typedef statement, which requires self discipline at the human level. The std template library uses the more reliable mechanism of traits, which are classes with no data and no methods, just typedefs, and from which iterator types inherit. Forward Iterators Forward iterators represent the most basic form of general purpose iterator. It is the only category of iterators guaranteed by the C++ standard to be supported by all of the container classes of the STL. (All of the containers in our class library actually support bidirectional iterators, but the vector container in the STL need not do so.) Forward iterators are those that have (at a minimum) all of the public interface shown in the slide. Note that these include tests for equality and non equality, element access via dereference, forward iteration, and all features associated with proper type. These are exactly the functionalities that enable the most basic kind of loop through a container, such as: Container C; Container::Iterator I; for (I = C.Begin(); I!= C.End(); ++I) cout << *I; These are also the functionalities assumed by all of the basic generic algorithms in tcpp/genalg.h. 1/9

2 Bidirectional Iterators Bidirectional iterators are forward iterators with the addition of the two decrement operators to the public interface. The containers List<>, TDeque<>, and TVector<> support bidirectional iterators, and array pointers can also be considered bidirectional iterators. Therefore all of the basic generic algorithms of tcpp/genalg.h may be applied to these types of container, mix and match. Moreover, the generic algorithms of tcpp/gset.h may also be applied to such containers, provided that the containers meet the other assumptions required by these algorithms. Random Access Iterators Random access iterators are bidirectional iterators with the additional features of random access, which means a bracket operator and "pointer" arithmetic (as shown in the slide). The containers TDeque<> and TVector<>, as well as ordinary arrays, support random access iterators. Therefore the generic algorithms of tcpp/gbsearch.h and tcpp/gheap.h may be applied to these types of containers, provided that the other assumptions of the individual algorithms are met. ConstIterators Every iterator type that is associated with a container type also has a version called ConstIterator. A ConstIterator operates with the same functionality as Iterator, except that a ConstIterator does not allow the container to be mutated, or changed, in any way. This is manifested in code as follows: X::Iterator i; X::ConstIterator ci; t = *i; // OK t = *ci; // OK *i = t; // OK *ci = t; // ERROR: attempted use of ci to mutate container (change value at ci) Note the distinction between ConstIterator and const Iterator. The former is itself mutable (we can, for example, call operator ++) but may not be used to mutate the container into which it points. The latter is itself constant, so it would need to be initialized at the point of declaration and could never be changed. The main use of ConstIterator is inside any block where the associated container is constant. In such a block, it is an error to declare an iterator, but OK to declare a ConstIterator: template < typename T > bool IsIn (const List<T> list, T searchval) // List<T>::Iterator i; // ERROR: const environment List<T>::ConstIterator i; // OK: using ConstIterator for (i = list.begin(); i!= list.end(); ++i) // calls "const" versions of Begin, End if (searchval == *i) return true; return false; Note that this code uses the (Const)Iterator only to read from the container. The support for ConstIterators is built in to the container class. A way to implement ConstIterators is explained in the next slide. 2/9

3 Container Support There is generally a tight coupling between a container and its associated iterator type (via declaration of mutual friendship). Moreover, for the container/iterator system to function appropriately there must be support for both terminology and ititialization iterators built in to the container. Terminology Support is illustrated in this code snippet (part of the definition of the container class X): template < typename T > class X... typedef typename I::Iterator typedef ConstRAIterator<I>... Iterator; ConstIterator; Initialization support is supplied via the Begin/End method pairs:... Iterator Begin(); ConstIterator Begin() const; Iterator End(); ConstIterator End() const;... Note the use of the const modifier to distinguish between the overloads of Begin() and End(). Input Iterators Input iterators are specialized toward the purpose of reading data from a source such as an istream where elements can be read but not written, and once passed they cannot be read again. Input iterators can be associated with istreams using adaptors. Input iterators have a dereference operator that is not fully functional in that it can only be used to read a value, not to write a value. In other words, if I is an input iterator, then v = *I; // OK for input iterators is a legal statement but *I = v; // not OK for input iterators is not. (That is, *I may be an rvalue but not an lvalue: it may appear only on the right side of an assignment.) This restriction might be enforced by returning a constant reference instead of a reference by the dereference operator, as illustrated in the slide. Note that this interface is barely enough to serve as the first iterator type for a generic algorithm such as g_copy() (copied here from tcpp/genalg.h): template <class I, class J> void g_copy (I source_beg, I source_end, J dest_beg) while (source_beg!= source_end) *dest_beg++ = *source_beg++; 3/9

4 Output Iterators Output iterators are specialized toward the purpose of writing data to a source such as an ostream or a container where elements can be written but not read, and once passed they cannot be written again. Output iterators can be associated with ostreams using adaptors. Insert iterators, defined below, are output iterators associated with containers. Output iterators have a dereference operator that is not fully functional in that it can only be used to write a value,but not to read a value. In other words, if I is an output iterator, then v = *I; // not OK for output iterators is a not legal statement but *I = v; // OK for output iterators is. (That is, *I may be an lvalue but not an rvalue: it may appear only on the left side of an assignment.) This restriction is enforced by the semantics of the particular output iterator. A typical case is illustrated in the slide, where the return value of operator *() is a (self)reference rather than a reference to a value. Note that this interface is barely enough to serve as the second iterator type for a generic algorithm such as g_copy(). The Iterator Hierarchy This slide illustrates the various iterator categories and how they relate among themselves. Not that these are NOT inheritance relationships in the usual sense of object oriented programming. They are inheritance relationships in the higher sense of patterns, which are often enforced by maintaining intellectual control of a development project. Pattern inheritance can also be enforced by inheritance of "traits", which are essentially classes with no data or functionality, only terminology defined using public typedef statements. The former approach is taken in this course. The latter approach is taken by the C++ STL. Iterator Adaptors Iterator adaptors are iterator classes obtained as adaptor classes of other classes. Suprisingly, sometimes the adaptee class is not an iterator class. ConstIterator ReverseIterator Insert Iterators Stream iterators are iterators adapted from stream classes and facilitate reading from/writing to streams with generic algorithms. Reverse iterators are adapted from forward iterators and serve to re define forward incrementation to be backward incrementation (i.e., decrementation). While not difficult subjects, we will not cover these topics in detail due to there minimal relevance to data structures and algorithms. ConstIterator Adaptor One way to implement ConstIterators for various containers is to define a single adaptor class and use it to adapt all of the container iterator classes. The idea is to just omit the non const versions of the dereference operator and bracket operator. The adaptor is defined for random access iterators, but can be 4/9

5 used for any other iterator type. // // ConstRAIterator<I> definition // template < class I > class ConstRAIterator public: // terminology support typedef typename I::ValueType ValueType; typedef typename I::PointerType PointerType; typedef typename I::ConstPointerType ConstPointerType; typedef typename I::ReferenceType ReferenceType; typedef typename I::ConstReferenceType ConstReferenceType; typedef typename I::ContainerType ContainerType; typedef typename I::Iterator Iterator; typedef ConstRAIterator<I> ConstIterator; // constructors ConstRAIterator (); ConstRAIterator (const ConstRAIterator& i); // copy constructor ConstRAIterator (const I& i); // type converter bool operator == (const ConstIterator& i2) const; bool operator!= (const ConstIterator& i2) const; ConstReferenceType operator * () const; // return element as R value ConstReferenceType operator [] (size_t index) const; // return element as R value ConstIterator& operator = (const ConstIterator & i); ConstIterator& operator ++ (); // prefix increment ConstIterator operator ++ (int); // postfix ConstIterator& operator (); // prefix decrement ConstIterator operator (int); // postfix // "pointer" arithmetic long operator (const ConstIterator & i2) const; // these are template member operators for pointer arithmetic ConstIterator operator + (N n) const; ConstIterator& operator += (N n); ConstIterator& operator = (N n); protected: I i_; ; // // ConstRAIterator<I> implementations // ConstRAIterator<I>::ConstRAIterator () : i_() 5/9

6 ConstRAIterator<I>::ConstRAIterator (const ConstRAIterator& i) : i_(i.i_) ConstRAIterator<I>::ConstRAIterator (const I& i) : i_(i) bool ConstRAIterator<I>::Valid () const return i_.valid(); bool ConstRAIterator<I>::operator == (const ConstRAIterator& i2) const return i_ == i2.i_; bool ConstRAIterator<I>::operator!= (const ConstRAIterator& i2) const return i_!= i2.i_; typename I::ConstReferenceType ConstRAIterator<I>::operator * () const return *i_; typename I::ConstReferenceType ConstRAIterator<I>::operator [] (size_t index) const return i_[index]; ConstRAIterator<I>& ConstRAIterator<I>::operator = (const ConstRAIterator & i) i_ = i.i_; ConstRAIterator<I>& ConstRAIterator<I>::operator ++ () ++i_; ConstRAIterator<I> ConstRAIterator<I>::operator ++ (int) ConstIterator i(*this); 6/9

7 operator ++(); return i; ConstRAIterator<I>& ConstRAIterator<I>::operator () i_; ConstRAIterator<I> ConstRAIterator<I>::operator (int) ConstIterator i(*this); operator (); return i; long ConstRAIterator<I>::operator (const ConstRAIterator<I> & i2) const return i_ i2.i_; ConstRAIterator<I> ConstRAIterator<I>::operator + (N n) const ConstIterator i = *this; i.i_ += n; return i; ConstRAIterator<I>& ConstRAIterator<I>::operator += (N n) i_ += n; ConstRAIterator<I>& ConstRAIterator<I>::operator = (N n) i_ = n; // useage: template < typename T > bool IsIn (const List<T> & list, T searchval) List<T>::ConstIterator i; for (i = list.begin(); i!= list.end(); ++i) // calls "const" versions of Begin, End if (searchval == *i) return true; return false; 7/9

8 Note that this one adaptor can be used for bidirectional and forward iterators because of the fact: template function code is compiled only when it is called in the program under compilation. Thus the random access features will be ignored when adapting bidirectional iterators and in addition the decrement operations will be ignored when adapting forward iterators. Insert Iterator Adaptors An important example of iterator adaptors, especially for use in the study of containers, is the insert iterator adaptor class. There are three versions, each of which overloads operator =() as an inserter into a container. Consider the following class definition: class PushBackIterator public: explicit PushBackIterator (C& x) : Cptr(&x) PushBackIterator <C>& operator = (const typename C::value_type& t) Cptr > PushBack(t); PushBackIterator<C>& operator * () PushBackIterator<C>& operator ++ () PushBackIterator<C>& operator ++ (int) protected: C* Cptr_; ; This class uses a container C with a PushBack() method to create an iterator that can do only one thing use operator *() as an lvalue to insert items at the back of the container. Note that this is actually accomplished by effectively removing functionality from operator *() and overloading the assignment operator. The operator *() and the increment operators are overloaded to perform no function other than to return a self reference. The following usage declares a list L and a PushBackIterator associated with L: List < char > L; PushBackIterator < List < char > > Litr(L); and the call g_copy(v.begin(), V.End(), Litr); has the effect of inserting all of the elements of the vector V to the back of the list L. The declaration of such a PushBackIterator is somewhat cumbersome, since it must be associated with a specific container as well as declared as to type. After the initial declaration, the following template function provides a useful shortcut to repeating the second line in the declaration above just to reassociate the iterator with a particular container object. It returns a PushBackIterator associated with the container. PushBackIterator<C> BackPusher (C& x) return PushBackIterator <C> (x); 8/9

9 // useage: Litr = BackPusher(L); The declaration and use of PushBackIterator adaptors is illustrated in the programs tests/fga.cpp and tests/fgset.cpp. Similar definitions hold for PushFrontIterator and InsertIterator adaptors, with these prototypes: class PushFrontIterator; PushFrontIterator<C> FrontPusher (C& x); class InsertIterator; InsertIterator<C> Inserter (C& x); All three insert iterator adaptor classes and supporting functions are given in tcpp/cinsert.h. 9/9

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 An important part of every container is the type of iterator it supports. This determines which algorithms can be applied to the container. A vector supports random-access iterators i.e., all iterator

More information

use static size for this buffer

use static size for this buffer Software Design (C++) 4. Templates and standard library (STL) Juha Vihavainen University of Helsinki Overview Introduction to templates (generics) std::vector again templates: specialization by code generation

More information

STL: C++ Standard Library

STL: C++ Standard Library STL: C++ Standard Library Encapsulates complex data structures and algorithms CSC 330 OO Software Design 1 We ve emphasized the importance of software reuse. Recognizing that many data structures and algorithms

More information

List, Stack, and Queues

List, Stack, and Queues List, Stack, and Queues R. J. Renka Department of Computer Science & Engineering University of North Texas 02/24/2010 3.1 Abstract Data Type An Abstract Data Type (ADT) is a set of objects with a set of

More information

I source_beg, source_end; // defines a range of values in a source container // defines the beginning of a range in a destination container

I source_beg, source_end; // defines a range of values in a source container // defines the beginning of a range in a destination container Generic Algorithms We have encountered and put to use the concept of generic classes, particularly generic containers. Generic containers could be characterized as implementations of ADTs that are re usable

More information

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms

STL components. STL: C++ Standard Library Standard Template Library (STL) Main Ideas. Components. Encapsulates complex data structures and algorithms STL: C++ Standard Library Standard Template Library (STL) Encapsulates complex data structures and algorithms is a library of generic container classes which are both efficient and functional C++ STL developed

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

More information

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Fall 2017 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

A linear structure is an ordered (e.g., sequenced) arrangement of elements. Lists, Stacks, and Queues 1 A linear structure is an ordered (e.g., sequenced) arrangement of elements. There are three common types of linear structures: list stack queue random insertion and deletion

More information

More Advanced Class Concepts

More Advanced Class Concepts More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators

More information

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

CS11 Advanced C++ Spring 2018 Lecture 2

CS11 Advanced C++ Spring 2018 Lecture 2 CS11 Advanced C++ Spring 2018 Lecture 2 Lab 2: Completing the Vector Last week, got the basic functionality of our Vector template working It is still missing some critical functionality Iterators are

More information

III. Classes (Chap. 3)

III. Classes (Chap. 3) III. Classes III-1 III. Classes (Chap. 3) As we have seen, C++ data types can be classified as: Fundamental (or simple or scalar): A data object of one of these types is a single object. int, double, char,

More information

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer

More information

SFU CMPT Topic: Class Templates

SFU CMPT Topic: Class Templates SFU CMPT-212 2008-1 1 Topic: Class Templates SFU CMPT-212 2008-1 Topic: Class Templates Ján Maňuch E-mail: jmanuch@sfu.ca Monday 3 rd March, 2008 SFU CMPT-212 2008-1 2 Topic: Class Templates Class templates

More information

Writing Generic Functions. Lecture 20 Hartmut Kaiser hkaiser/fall_2013/csc1254.html

Writing Generic Functions. Lecture 20 Hartmut Kaiser  hkaiser/fall_2013/csc1254.html Writing Generic Functions Lecture 20 Hartmut Kaiser hkaiser@cct.lsu.edu http://www.cct.lsu.edu/ hkaiser/fall_2013/csc1254.html Code Quality Programming Principle of the Day Minimize Coupling - Any section

More information

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects Vectors of Objects As we have mentioned earlier, you should almost always use vectors instead of arrays. If you need to keep track of persons (objects of class Person), you must decide what to store in

More information

Standard Library Reference

Standard Library Reference Standard Library Reference This reference shows the most useful classes and functions in the standard library. Note that the syntax [start, end) refers to a half-open iterator range from start to end,

More information

Templates and Vectors

Templates and Vectors Templates and Vectors 1 Generic Programming function templates class templates 2 the STL vector class a vector of strings enumerating elements with an iterator inserting and erasing 3 Writing our own vector

More information

Program construction in C++ for Scientific Computing

Program construction in C++ for Scientific Computing 1 (26) School of Engineering Sciences Program construction in C++ for Scientific Computing 2 (26) Outline 1 2 3 4 5 6 3 (26) Our Point class is a model for the vector space R 2. In this space, operations

More information

1. The term STL stands for?

1. The term STL stands for? 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 2. Which of the following statements regarding the

More information

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists

CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists CSCI-1200 Data Structures Spring 2018 Lecture 10 Vector Iterators & Linked Lists Review from Lecture 9 Explored a program to maintain a class enrollment list and an associated waiting list. Unfortunately,

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

Programming in C++ using STL. Rex Jaeschke

Programming in C++ using STL. Rex Jaeschke Programming in C++ using STL Rex Jaeschke Programming in C++ using STL 1997, 1999, 2002, 2007, 2009 Rex Jaeschke. All rights reserved. Edition: 2.0 All rights reserved. No part of this publication may

More information

Doubly-Linked Lists

Doubly-Linked Lists Doubly-Linked Lists 4-02-2013 Doubly-linked list Implementation of List ListIterator Reading: Maciel, Chapter 13 HW#4 due: Wednesday, 4/03 (new due date) Quiz on Thursday, 4/04, on nodes & pointers Review

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles Abstract Data Types (ADTs) CS 247: Software Engineering Principles ADT Design An abstract data type (ADT) is a user-defined type that bundles together: the range of values that variables of that type can

More information

CS 247: Software Engineering Principles. ADT Design

CS 247: Software Engineering Principles. ADT Design CS 247: Software Engineering Principles ADT Design Readings: Eckel, Vol. 1 Ch. 7 Function Overloading & Default Arguments Ch. 12 Operator Overloading U Waterloo CS247 (Spring 2017) p.1/17 Abstract Data

More information

CS11 Advanced C++ Fall Lecture 1

CS11 Advanced C++ Fall Lecture 1 CS11 Advanced C++ Fall 2006-2007 Lecture 1 Welcome! ~8 lectures Slides are posted on CS11 website http://www.cs.caltech.edu/courses/cs11 ~6 lab assignments More involved labs 2-3 week project at end CS

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

Advanced Programming in C++ Container Design I

Advanced Programming in C++ Container Design I Advanced Programming in C++ Container Design I This is an exercise on container design, especially in the view of robustness, iterators, and storage management. The container will be developed step-by-step,

More information

Introduction. Programming in C++ Pointers and arrays. Pointers in C and C++ Session 5 - Pointers and Arrays Iterators

Introduction. Programming in C++ Pointers and arrays. Pointers in C and C++ Session 5 - Pointers and Arrays Iterators Session 5 - Pointers and Arrays Iterators Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) Introduction Pointers and arrays: vestiges

More information

Stacks and their Applications

Stacks and their Applications Stacks and their Applications Lecture 23 Sections 18.1-18.2 Robb T. Koether Hampden-Sydney College Fri, Mar 16, 2018 Robb T. Koether Hampden-Sydney College) Stacks and their Applications Fri, Mar 16, 2018

More information

Iterator Facade. Table of Contents. Overview. Usage. Iterator Core Access operator[] operator-> Reference

Iterator Facade. Table of Contents. Overview. Usage. Iterator Core Access operator[] operator-> Reference Iterator Facade Author: Contact: Organization: David Abrahams, Jeremy Siek, Thomas Witt dave@boost-consulting.com, jsiek@osl.iu.edu, witt@ive.uni-hannover.de Boost Consulting, Indiana University Open Systems

More information

Table of Contents. Overview. Usage. Iterator Core Access. operator[] operator-> Reference

Table of Contents. Overview. Usage. Iterator Core Access. operator[] operator-> Reference Iterator Facade 2 Author: David Abrahams, Jeremy Siek, Thomas Witt Contact: dave@boost-consulting.com, jsiek@osl.iu.edu, witt@ive.uni-hannover.de Organization: Boost Consulting, Indiana University Open

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

Exercise 6.2 A generic container class

Exercise 6.2 A generic container class Exercise 6.2 A generic container class The goal of this exercise is to write a class Array that mimics the behavior of a C++ array, but provides more intelligent memory management a) Start with the input

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

std::cout << "Size of long = " << sizeof(long) << " bytes\n\n"; std::cout << "Size of char = " << sizeof(char) << " bytes\n";

std::cout << Size of long =  << sizeof(long) <<  bytes\n\n; std::cout << Size of char =  << sizeof(char) <<  bytes\n; C++ Program Structure A C++ program must adhere to certain structural constraints. A C++ program consists of a sequence of statements. Every program has exactly one function called main. Programs are built

More information

UNIT- 3 Introduction to C++

UNIT- 3 Introduction to C++ UNIT- 3 Introduction to C++ C++ Character Sets: Letters A-Z, a-z Digits 0-9 Special Symbols Space + - * / ^ \ ( ) [ ] =!= . $, ; : %! &? _ # = @ White Spaces Blank spaces, horizontal tab, carriage

More information

The following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs.

The following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs. The following is an excerpt from Scott Meyers new book, Effective C++, Third Edition: 55 Specific Ways to Improve Your Programs and Designs. Item 47: Use traits classes for information about types. The

More information

General Advise: Don t reinvent the wheel

General Advise: Don t reinvent the wheel General Advise: Don t reinvent the wheel Use libraries: Discover the available open source libraries for your application Examples: STL, boost, thrust libraries Info on C++ and STL: http://www.cplusplus.com/reference,

More information

A linear structure is an ordered (e.g., sequenced) arrangement of elements.

A linear structure is an ordered (e.g., sequenced) arrangement of elements. Lists, Stacks, and Queues 1 A linear structure is an ordered (e.g., sequenced) arrangement of elements. There are three common types of linear structures: list stack queue random insertion and deletion

More information

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it?

Review. What is const member data? By what mechanism is const enforced? How do we initialize it? How do we initialize it? Review Describe pass-by-value and pass-by-reference Why do we use pass-by-reference? What does the term calling object refer to? What is a const member function? What is a const object? How do we initialize

More information

Lab 6. Out: Wednesday 9 March 2005

Lab 6. Out: Wednesday 9 March 2005 CS034 Intro to Systems Programming Doeppner & Van Hentenryck What you ll learn. Lab 6 Out: Wednesday 9 March 2005 Modern C++ comes with a powerful template library, the Standard Template Library, or STL.

More information

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides.

Lecture 21 Standard Template Library. A simple, but very limited, view of STL is the generality that using template functions provides. Lecture 21 Standard Template Library STL: At a C++ standards meeting in 1994, the committee voted to adopt a proposal by Alex Stepanov of Hewlett-Packard Laboratories to include, as part of the standard

More information

Object-Oriented Programming for Scientific Computing

Object-Oriented Programming for Scientific Computing Object-Oriented Programming for Scientific Computing Traits and Policies Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 11. Juli 2017

More information

Chapter 5. The Standard Template Library.

Chapter 5. The Standard Template Library. Object-oriented programming B, Lecture 11e. 1 Chapter 5. The Standard Template Library. 5.1. Overview of main STL components. The Standard Template Library (STL) has been developed by Alexander Stepanov,

More information

CS197c: Programming in C++

CS197c: Programming in C++ CS197c: Programming in C++ Lecture 2 Marc Cartright http://ciir.cs.umass.edu/~irmarc/cs197c/index.html Administration HW1 will be up this afternoon Written assignment Due in class next week See website

More information

Assignment 1: grid. Due November 20, 11:59 PM Introduction

Assignment 1: grid. Due November 20, 11:59 PM Introduction CS106L Fall 2008 Handout #19 November 5, 2008 Assignment 1: grid Due November 20, 11:59 PM Introduction The STL container classes encompass a wide selection of associative and sequence containers. However,

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Question Paper Code : 97044

Question Paper Code : 97044 Reg. No. : Question Paper Code : 97044 B.E./B.Tech. DEGREE EXAMINATION NOVEMBER/DECEMBER 2014 Third Semester Computer Science and Engineering CS 6301 PROGRAMMING AND DATA STRUCTURES-II (Regulation 2013)

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

2 nd Week Lecture Notes

2 nd Week Lecture Notes 2 nd Week Lecture Notes Scope of variables All the variables that we intend to use in a program must have been declared with its type specifier in an earlier point in the code, like we did in the previous

More information

Overloaded Operators, Functions, and Students

Overloaded Operators, Functions, and Students , Functions, and Students Division of Mathematics and Computer Science Maryville College Outline Overloading Symbols 1 Overloading Symbols 2 3 Symbol Overloading Overloading Symbols A symbol is overloaded

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types.

Polymorphism. Programming in C++ A problem of reuse. Swapping arguments. Session 4 - Genericity, Containers. Code that works for many types. Session 4 - Genericity, Containers Polymorphism Code that works for many types. Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson)

More information

Introduction to Programming using C++

Introduction to Programming using C++ Introduction to Programming using C++ Lecture One: Getting Started Carl Gwilliam gwilliam@hep.ph.liv.ac.uk http://hep.ph.liv.ac.uk/~gwilliam/cppcourse Course Prerequisites What you should already know

More information

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 8 Operator Overloading, Friends, and References Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Basic Operator Overloading Unary operators As member functions Friends

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

ADTs & Classes. An introduction

ADTs & Classes. An introduction ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object

More information

Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019

Overload Resolution. Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 Ansel Sermersheim & Barbara Geller Amsterdam C++ Group March 2019 1 Introduction Prologue Definition of Function Overloading Determining which Overload to call How Works Standard Conversion Sequences Examples

More information

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

Programming C++ Lecture 6. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Programming C++ Lecture 6 Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor Jennifer.sartor@elis.ugent.be S Friends 2 Friends of Objects S Classes sometimes need friends. S Friends are defined outside

More information

Value categories. PRvalues. Lvalues

Value categories. PRvalues. Lvalues Value categories v5 Every C++14 expression belongs to exactly one of the following classifications, known as value categories: lvalue, xvalue, prvalue. There's an overlap between these, so a higher level

More information

C++ Programming Chapter 7 Pointers

C++ Programming Chapter 7 Pointers C++ Programming Chapter 7 Pointers Yih-Peng Chiou Room 617, BL Building (02) 3366-3603 ypchiou@cc.ee.ntu.edu.tw Photonic Modeling and Design Lab. Graduate Institute of Photonics and Optoelectronics & Department

More information

G52CPP C++ Programming Lecture 17

G52CPP C++ Programming Lecture 17 G52CPP C++ Programming Lecture 17 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last Lecture Exceptions How to throw (return) different error values as exceptions And catch the exceptions

More information

15. Pointers, Algorithms, Iterators and Containers II

15. Pointers, Algorithms, Iterators and Containers II 498 Recall: Pointers running over the Array 499 Beispiel 15. Pointers, Algorithms, Iterators and Containers II int a[5] = 3, 4, 6, 1, 2; for (int p = a; p < a+5; ++p) std::cout

More information

Pairing off iterators

Pairing off iterators Pairing off iterators Anthony Williams 8th May 2002 1 Introduction Recently, a colleague approached me with an interesting problem; he had two containers with corresponding elements, so the n-th entry

More information

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11

Container Notes. Di erent Kinds of Containers. Types Defined by Containers. C++11 Container Notes C++11 Di erent Kinds of Containers Container Notes A container is an object that stores other objects and has methods for accessing the elements. There are two fundamentally di erent kinds of containers: Sequences

More information

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects

Iterators. node UML diagram implementing a double linked list the need for a deep copy. nested classes for iterator function objects Iterators 1 Double Linked and Circular Lists node UML diagram implementing a double linked list the need for a deep copy 2 Iterators on List nested classes for iterator function objects MCS 360 Lecture

More information

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture:

CISC 2200 Data Structure Fall, C++ Review:3/3. 1 From last lecture: CISC 2200 Data Structure Fall, 2016 C++ Review:3/3 1 From last lecture: pointer type and pointer variable (stores memory addresses of a variable (of any type, local or global, automatic/static/dynamic)

More information

pointers & references

pointers & references pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using

More information

G52CPP C++ Programming Lecture 18. Dr Jason Atkin

G52CPP C++ Programming Lecture 18. Dr Jason Atkin G52CPP C++ Programming Lecture 18 Dr Jason Atkin 1 Last lecture Operator Overloading Strings and streams 2 Operator overloading - what to know Know that you can change the meaning of operators Know that

More information

Outline. 1 About the course

Outline. 1 About the course Outline EDAF50 C++ Programming 1. Introduction 1 About the course Sven Gestegård Robertz Computer Science, LTH 2018 2 Presentation of C++ History Introduction Data types and variables 1. Introduction 2/1

More information

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018

Overload Resolution. Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 Ansel Sermersheim & Barbara Geller ACCU / C++ June 2018 1 Introduction Definition of Function Overloading Determining which Overload to call How Overload Resolution Works Standard Conversion Sequences

More information

Data Types and Variables in C language

Data Types and Variables in C language Data Types and Variables in C language Disclaimer The slides are prepared from various sources. The purpose of the slides is for academic use only Operators in C C supports a rich set of operators. Operators

More information

G52CPP C++ Programming Lecture 18

G52CPP C++ Programming Lecture 18 G52CPP C++ Programming Lecture 18 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Welcome Back 2 Last lecture Operator Overloading Strings and streams 3 Operator overloading - what to know

More information

PIC10B/1 Winter 2014 Exam I Study Guide

PIC10B/1 Winter 2014 Exam I Study Guide PIC10B/1 Winter 2014 Exam I Study Guide Suggested Study Order: 1. Lecture Notes (Lectures 1-8 inclusive) 2. Examples/Homework 3. Textbook The midterm will test 1. Your ability to read a program and understand

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information

AIMS Embedded Systems Programming MT 2017

AIMS Embedded Systems Programming MT 2017 AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors

More information

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2 TEMPLATES Today This lecture looks at techniques for generic programming: Generic pointers Templates The standard template library Thebestreferenceis: http://www.cppreference.com/index.html andyoucanalsoconsultchapters6amd7inthetextbook.

More information

14. Pointers, Algorithms, Iterators and Containers II

14. Pointers, Algorithms, Iterators and Containers II Recall: Pointers running over the Array Beispiel 14. Pointers, Algorithms, Iterators and Containers II Iterations with Pointers, Arrays: Indices vs. Pointers, Arrays and Functions, Pointers and const,

More information

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008

COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008 COP4530 Data Structures, Algorithms and Generic Programming Recitation 4 Date: September 14/18-, 2008 Lab topic: 1) Take Quiz 4 2) Discussion on Assignment 2 Discussion on Assignment 2. Your task is to

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Introduction p. xxix The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Language p. 6 C Is a Programmer's Language

More information

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction CS106L Spring 2009 Handout #21 May 12, 2009 static Introduction Most of the time, you'll design classes so that any two instances of that class are independent. That is, if you have two objects one and

More information

Lesson 13 - Vectors Dynamic Data Storage

Lesson 13 - Vectors Dynamic Data Storage Lesson 13 - Vectors Dynamic Data Storage Summary In this lesson we introduce the Standard Template Library by demonstrating the use of Vectors to provide dynamic storage of data elements. New Concepts

More information

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4

Sets and MultiSets. Contents. Steven J. Zeil. July 19, Overview of Sets and Maps 4 Steven J. Zeil July 19, 2013 Contents 1 Overview of Sets and Maps 4 1 2 The Set ADT 6 2.1 The template header................................. 14 2.2 Internal type names.................................

More information

Faculty of Information and Communication Technologies

Faculty of Information and Communication Technologies Swinburne University Of Technology Faculty of Information and Communication Technologies ASSIGNMENT COVER SHEET Subject Code: Subject Title: Assignment number and title: Due date: Lecturer: HIT3303 Data

More information

Topics. bool and string types input/output library functions comments memory allocation templates classes

Topics. bool and string types input/output library functions comments memory allocation templates classes C++ Primer C++ is a major extension of c. It is similar to Java. The lectures in this course use pseudo-code (not C++). The textbook contains C++. The labs involve C++ programming. This lecture covers

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more gene

void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more gene Passing arrays to functions A big topic for beginners is how to write a function that can be passed an array. A very common way of achieving this is done using pointers. This method can be seen all through

More information

Interview Questions of C++

Interview Questions of C++ Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.

More information