1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES AND ALGORITHMS Prepared by İnanç TAHRALI
Advertisements

1 Linked lists Sections 3.2, 3.3, 3.5 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors.
1111 Abstract Data Types Cpt S 223. School of EECS, WSU.
The List ADT Textbook Sections
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,
More on the STL vector list stack queue priority_queue.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Main Index Contents 11 Main Index Contents Container Types Container Types Sequence Containers Sequence Containers Associative Containers Associative Containers.
Standard Template Library. Homework List HW will be posted on webpage Due Nov 15.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
Lecture 11 Standard Template Library Stacks, Queue, and Deque Lists Iterators Sets Maps.
Templates and the STL.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Sorting and Vectors Mechanism for representing lists JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
ECE 250 Algorithms and Data Structures Douglas Wilhelm Harder, M.Math. LEL Department of Electrical and Computer Engineering University of Waterloo Waterloo,
Dr. Yingwu Zhu STL Vector and Iterators. STL (Standard Template Library) 6:14:43 AM 2 A library of class and function templates Components: 1. Containers:
Data Structures Using C++ 2E
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector.
Containers Overview and Class Vector
1 CSC 222: Computer Programming II Spring 2004 Pointers and linked lists  human chain analogy  linked lists: adding/deleting/traversing nodes  Node.
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.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
Main Index Contents 11 Main Index Contents Week 3 – The Vector Container.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementations:
STL multimap Container. STL multimaps multimaps are associative containers –Link a key to a value –AKA: Hashtables, Associative Arrays –A multimap allows.
Data Structures Using C++
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.
1 Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors Section 3.5, class notes Iterators Generic algorithms.
Chapter 9: Part 2: Vectors + Maps and STL Overview JPC and JWD © 2002 McGraw-Hill, Inc. Modified by S. Sudarshan.
Friends & Standard Template Library CSCI3110 Advanced Data Structures Lecturer: Dr. Carroll and Nan Chen.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Stacks.
Standard Template Library The Standard Template Library was recently added to standard C++. –The STL contains generic template classes. –The STL permits.
Copyright © 2012 Pearson Education, Inc. Chapter 17: Linked Lists.
1 Chapter 1 C++ Templates Sections 1.6 and Templates Type-independent patterns that can work with multiple data types –Generic programming –Code.
A gentle introduction to the standard template library (STL) Some references:
The Standard Template Library Container Classes Version 1.0.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Data Structure Specification  Language independent  Abstract Data Type  C++  Abstract Class.
CS 201 Data Structures and Algorithms Chapter 3: Lists, Stacks, and Queues - I Text: Read Weiss, §3.1 – 3.5 1Izmir University of Economics.
Chapter 3 Templates. Objective In Chapter 3, we will discuss: The concept of a template Function templates Class templates vector and matrix classes Fancy.
The List ADT Reading: Sections 3.2, 3.3, 3.5.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
ICOM 4035 – Data Structures Dr. Manuel Rodríguez Martínez Electrical and Computer Engineering Department Lecture 5 – September 4 th, 2001.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 223 – Advanced Data Structures C++ Review 2.
1 Circular, Doubly-Linked Lists Node Composition List Class Pushing and Popping Values Insert and Erase at Arbitrary Locations List Implementation.
Introduction to Data Structure, Fall 2006 Slide- 1 California State University, Fresno Introduction to Data Structure Chapter 4 Ming Li Department of Computer.
1 Linked Multiple Queues. 2 A real world example. Not in the book. Sometimes we have a fixed number of items that move around among a fixed set of queues.
Vectors. Basics A vector is like an array, but more flexible A vector provides (constant time) random access to its elements A vector may be dynamically.
CSCI  Sequence Containers – store sequences of values ◦ vector ◦ deque ◦ list  Associative Containers – use “keys” to access data rather than.
Standard Template Library a collection of useful tools.
1 Generic Positional Containers and Double-Ended Queues.
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.
Data Structure and Algorithm Analysis 03: Lists, Stacks and Queues Hongfei Yan School of EECS, Peking University.
Cpt S 122 – Data Structures Abstract Data Types
Vectors Holds a set of elements, like an array
Lists The List ADT.
What remains Topics Assignments Final exam
Chapter 16-2 Linked Structures
Abstract Data Types Iterators Vector ADT Sections 3.1, 3.2, 3.3, 3.4
Object Oriented Programming COP3330 / CGS5409
Chapter 3 Lists, Stacks, and Queues Abstract Data Types, Vectors
Doubly Linked List Implementation
Lists - I The List ADT.
Lists - I The List ADT.
Doubly Linked List Implementation
Chapter 3 Lists, Stacks, and Queues
The List Container and Iterators
Presentation transcript:

1 Chapter 3 Lists, Stacks, and Queues Reading: Sections 3.1, 3.2, 3.3, 3.4 Abstract Data Types (ADT) Iterators Implementation of Vector

2 Abstract Data Type (ADT) High-level definition of data types An ADT specifies –A collection of data –A set of operations on the data or subsets of the data ADT does not specify how the operations should be implemented Examples –list, stack, queue, deque, priority queue, table (map), associative array, set, graph, digraph How are they different: –Class –Class template –ADT

3 List ADT Objects/data –A 0, A 1, A 2, … A N-1 –Size of the List is N Operations –Up to the designer of a List, for example, –printList() –makeEmpty() –Find() –Insert() –Remove() –findKth() –etc

4 Iterators: motivation Need a way to navigate through the items in a container. An example: navigating over vector v. for (int i = 0; i != v.size(); i++ ) cout << v[i] << endl; However, doubly-linked list would need a different form We want a general approach to navigate elements for different implementations of an ADT

5 Iterators A generalized type that helps in navigating any container –A way to initialize at the front and back of a list –A way to move to the next or previous position –A way to detect the end of an iteration –A way to retrieve the current value Implemented as nested types of containers in STL Examples: –Iterator type for vector defined as vector ::iterator itr; –Iterator type for list defined as list ::iterator itr;

6 Getting an Iterator Two methods in all STL containers –iterator begin ( ) Returns an iterator to the first item in the container –iterator end ( ) Returns an iterator representing end marker in the container (i.e. the position after the last item) Example: for (int i = 0; i != v.size(); i++ ) cout << v[i] << endl; can be written using iterators as for(vector ::iterator itr=v.begin(); itr!=v.end(); itr.???) cout << itr.??? << endl; What about ??? –Methods associated with iterators

7 Iterator Methods Iterators have methods Many methods use operator overloading –itr++ and ++itr  advance the iterator to next location –*itr  return reference to object stored at iterator itr’s location – itr1 == itr2  true if itr1 and itr2 refer to the same location, else false – itr1 != itr2  true if itr1 and itr2 refer to different locations, else false Previous example becomes for(vector ::iterator itr=v.begin(); itr!=v.end(); itr++) cout << *itr << endl; Alternatively vector ::iterator itr = v.begin( ); while( itr != v.end( ) ) cout << *itr++ << endl; Since C++11, we can use auto instead of specifying type –auto itr = v.begin();

8 Container operations requiring iterators Adding element –iterator insert(iterator pos, const object &x) –Add x in list before iterator pos –Returns iterator representing position of inserted item Removing element –iterator erase(iterator pos) –Remove element at position pos –Returns iterator representing position of item following pos Removing elements in a range –iterator erase(iterator start, iterator end) –Remove elements from start to end (not including end )

9 Iterator example Removing every other elements in a list Before C++11 typename Container::iterator itr = lst.begin(); template void removeEveryOtherItem( Container & lst ) { auto itr = lst.begin( );// C++11 while( itr != lst.end( ) ) { itr = lst.erase( itr ); if( itr != lst.end( ) ) ++itr; }

10 const_iterator The following code was illegal Two versions of begin() and two versions of end() –iterator begin() –const_iterator begin() –iterator end() –const_iterator end() template void print (const Container &lst, ostream &out = cout) { typename Constainer::iterator itr = lst.begin(); while (itr != lst.end()) { out << *itr << endl; *itr = 0; itr++; }

11 const_iterator Note that c.begin() and c.end() functions in the example return const_iterator type. Returns a constant reference for operator* So that a function does not try to modify the elements of a constant container object. template void print( const Container & c, ostream & out = cout ) { if( c.empty( ) ) out << "(empty)"; else { auto itr = begin( c ); // auto itr = c.begin(); // typename Container::const_iterator itr = c.begin(); out << "[ " << *itr++; // Print first item while( itr != end( c ) ) // while (itr != c.begin()) out << ", " << *itr++; out << " ]" << endl; }

12 The Vector Implementation of List ADT Extends the notion of array by storing a sequence of arbitrary objects –Informally, we call it Vector ADT Elements of vector ADT can be accessed by specifying their index.

13 vector in C++ STL Collection  Elements of some proper type T Operations –int size ( )  returns the number of elements in the vector –void clear ( )  removes all elements from the vector –bool empty ( )  returns true if the vector has no elements –void push_back ( const Object &x ) adds x to the end of the vector –void pop_back ( ) Removes the object at the end of the vector –Object & back ( ) Returns the object at the end of the vector –Object & front ( ) Returns the object at the front of the vector

14 vector in C++ STL (contd.) More Operations –Object & operator[] ( int index ) Returns the object at location index (without bounds checking) Both accessor and mutator versions –Object & at ( int index ) Returns the object at location index (with bounds checking) –int capacity ( ) Returns the internal capacity of the vector Number of elements the container can hold without further memory allocation –void reserve ( int newCapacity) Sets the new capacity of the vector Number of elements that the container can hold –void resize ( int newSize, const Object& val = Object() ) Change the size of the vector Newly created elements will be initialized to val

15 Implementing Vector Class Template Implementing Vector as first-class type –Can be copied –Memory it uses automatically reclaimed Vector maintains –A primitive C++ array –The array capacity –The current number of items stored in the Vector Operations: –Copy and move constructor –Copy and move assignment operator= –Destructor to reclaim primitive array. –All the other operators we saw earlier.

template class Vector { public: explicit Vector( int initSize = 0 )// constructor : theSize{ initSize }, theCapacity{ initSize + SPARE_CAPACITY } { objects = new Object[ theCapacity ]; } Vector( const Vector & rhs )// copy constructor : theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ nullptr } { objects = new Object[ theCapacity ]; for( int k = 0; k < theSize; ++k ) objects[ k ] = rhs.objects[ k ]; } Vector & operator= ( const Vector & rhs )// copy assignment operator= { Vector copy = rhs;// calling copy constructor std::swap( *this, copy ); return *this; } 16 Vector Implementation (Part 1)

~Vector( ) { delete [ ] objects; } Vector( Vector && rhs )// move constructor : theSize{ rhs.theSize }, theCapacity{ rhs.theCapacity }, objects{ rhs.objects } { rhs.objects = nullptr; rhs.theSize = 0; rhs.theCapacity = 0; } Vector & operator= ( Vector && rhs )// move assignment operator= { std::swap( theSize, rhs.theSize ); std::swap( theCapacity, rhs.theCapacity ); std::swap( objects, rhs.objects ); return *this; } 17 Vector Implementation (Part 2)

bool empty( ) const { return size( ) == 0; } int size( ) const { return theSize; } int capacity( ) const { return theCapacity; } Object & operator[]( int index ) { return objects[ index ];// no error checking } const Object & operator[]( int index ) const { return objects[ index ];// no error checking } void resize( int newSize ) { if( newSize > theCapacity ) reserve( newSize * 2 );// memory allocation is expensive theSize = newSize; } 18 Vector Implementation (Part 3)

void reserve( int newCapacity ) { if( newCapacity < theSize ) return; Object *newArray = new Object[ newCapacity ]; for( int k = 0; k < theSize; ++k ) newArray[ k ] = std::move( objects[ k ] ); theCapacity = newCapacity; std::swap( objects, newArray ); delete [ ] newArray; } void push_back( const Object & x )// copy x { if( theSize == theCapacity ) reserve( 2 * theCapacity + 1 );// memory allocation is expensive objects[ theSize++ ] = x; } 19 Vector Implementation (Part 4)

Vector Implementation (Part 5) void push_back( Object && x )// move x { if( theSize == theCapacity ) reserve( 2 * theCapacity + 1 ); objects[ theSize++ ] = std::move( x ); } void pop_back( ) { --theSize; } const Object & back ( ) const { return objects[ theSize - 1 ]; } // Iterator stuff: not bounds checked typedef Object * iterator;// defined as pointer to object, not real nested class typedef const Object * const_iterator; 20

Vector Implementation (Part 6) iterator begin( ) { return &objects[ 0 ]; } const_iterator begin( ) const { return &objects[ 0 ]; } iterator end( ) { return &objects[ size( ) ]; } const_iterator end( ) const { return &objects[ size( ) ]; } static const int SPARE_CAPACITY = 16; private: int theSize;// number of actual elements int theCapacity;// number of elements that can be stored without reallocating memory Object * objects; }; 21

22 Reading assignment Sections 3.2, 3.3, and 3.5