Introduction to ADTs

Similar documents
Introduction to ADTs

III. Classes (Chap. 3)

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Linked Lists. Linked list: a collection of items (nodes) containing two components: Data Address (link) of the next node in the list

Chapter 15 - C++ As A "Better C"

CSCE 110 PROGRAMMING FUNDAMENTALS

Review Questions for Final Exam

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

TDDD38 - Advanced programming in C++

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

Unit 1: Preliminaries Part 4: Introduction to the Standard Template Library

CSC 222: Computer Programming II. Spring 2004

Purpose of Review. Review some basic C++ Familiarize us with Weiss s style Introduce specific constructs useful for implementing data structures

Absolute C++ Walter Savitch

STL: C++ Standard Library

CS2255 HOMEWORK #1 Fall 2012

CMSC 341 Lecture 6 STL, Stacks, & Queues. Based on slides by Lupoli, Dixon & Gibson at UMBC

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

! An exception is a condition that occurs at execution time and makes normal continuation of the program impossible.

EECE.3220: Data Structures Spring 2017

CS2141 Software Development using C/C++ C++ Basics

(8 1) Container Classes & Class Templates D & D Chapter 18. Instructor - Andrew S. O Fallon CptS 122 (October 8, 2018) Washington State University

CSC212. Data Structure. Lecture 4 Container Classes. Instructor: George Wolberg Department of Computer Science City College of New York

use static size for this buffer

COEN244: Class & function templates

Unit 4 Basic Collections

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

Computational Physics

Lecture-5. STL Containers & Iterators

CS197c: Programming in C++

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

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

CSCI-1200 Data Structures Fall 2017 Lecture 9 Iterators & STL Lists

Due Date: See Blackboard

1. The term STL stands for?

CE221 Programming in C++ Part 1 Introduction

Class and Function Templates

Motivation for Templates. Class and Function Templates. One Way to Look at Templates...

Chapter 5. The Standard Template Library.

Introduction to C++ Systems Programming

Lecture 7. Log into Linux New documents posted to course webpage

Heaps. A complete binary tree can be easily stored in an array - place the root in position 1 (for convenience)

STL Standard Template Library

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CSE030 Fall 2012 Final Exam Friday, December 14, PM

CS201 - Introduction to Programming Glossary By

Motivation for Templates

Review for Test 1 (Chapter 1-5)

CS 247: Software Engineering Principles. ADT Design

CSCI-1200 Data Structures Fall 2014 Lecture 8 Iterators

Review Questions for Final Exam KEY

AN OVERVIEW OF C++ 1

Lab 2: ADT Design & Implementation

CSCI-1200 Data Structures Fall 2010 Lecture 8 Iterators

CSI33 Data Structures

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

When we program, we have to deal with errors. Our most basic aim is correctness, but we must

Dynamic Data Structures

Short Notes of CS201

PIC10B/1 Winter 2014 Exam I Study Guide

Due Date: See Blackboard

UEE1302 (1102) F10: Introduction to Computers and Programming

List, Stack, and Queues

Introducing C++ to Java Programmers

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

Introduction to C++ Introduction to C++ 1

! Search: find a given target item in an array, ! Linear Search: Very simple search method: ! Operators such as =, +, <, and others can be

The Standard Template Library. An introduction

Lesson 13 - Vectors Dynamic Data Storage

Integer Data Types. Data Type. Data Types. int, short int, long int

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Ch 4 Pointers and Dynamic Arrays

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CPSC 427a: Object-Oriented Programming

C++ Functions. Last Week. Areas for Discussion. Program Structure. Last Week Introduction to Functions Program Structure and Functions

Lecture 8. Xiaoguang Wang. February 13th, 2014 STAT 598W. (STAT 598W) Lecture 8 1 / 47

Arrays and Linked Lists

Lectures 4 & 5 Container Classes

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

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

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

Templates and Vectors

Chapter 18 - C++ Operator Overloading

CS 216 Exam 1 Fall SOLUTION

ADTs & Classes. An introduction

19.1 The Standard Template Library

Operator Overloading and Templates. Linear Search. Linear Search in C++ second attempt. Linear Search in C++ first attempt

Programming Abstractions

CSE 333. Lecture 9 - intro to C++ Hal Perkins Department of Computer Science & Engineering University of Washington

Example Final Questions Instructions

Container Class and Integrators, Proxy Class EC6301-OOPS AND DATA STRUCTURES

1 Short Answer (7 Points Each)

DATA STRUCTURES AND ALGORITHMS LECTURE 08 QUEUES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD

2 ADT Programming User-defined abstract data types

Due Date: See Blackboard

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Transcription:

Data Structure Introduction to ADTs A particular way of storing and organizing data in a computer so that it can be used efficiently *from Wikipedia A set of data values and associated operations that are precisely specified independent of any particular implementation. *from http://xlinux.nist.gov/dads/ A data type having - A specific, physical or logical representation of the data - Operations over its data A concrete and logical description May be implemented in various ways - Implementation-dependent Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. Example Let's take one real life example of a TV, which you can turn on and off, change the channel, adjust the volume, and add external components such as speakers, VCRs, and DVD players, BUT you do not know its internal details, that is, you do not know how it receives signals over the air or through a cable, how it translates them, and finally displays them on the screen. Thus, we can say a television clearly separates its internal implementation from its external interface and you can play with its interfaces like the power button, channel changer, and volume control without having zero knowledge of its internals. Spring 2018 CS3358 - Husain Gholoom Page 1

Example Your program can make a call to the sort() function without knowing what algorithm the function actually uses to sort the given values. In fact, the underlying implementation of the sorting functionality could change between releases of the library, and as long as the interface stays the same, your function call will still work. In C++, we use classes to define our own abstract data types (ADT). You can use the cout object of class iostream to stream data to standard output like this: #include <iostream> using namespace std; int main( ) cout << "Hello C++" <<endl; return 0; Here, you don't need to understand how cout displays the text on the user's screen. You need to only know the public interface and the underlying implementation of cout is free to change. Access Labels Enforce Abstraction: In C++, we use access labels to define the abstract interface to the class. A class may contain zero or more access labels: Members defined with a public label are accessible to all parts of the program. The data-abstraction view of a type is defined by its public members. Members defined with a private label are not accessible to code that uses the class. The private sections hide the implementation from code that uses the type Spring 2018 CS3358 - Husain Gholoom Page 2

Data Abstraction Example: Any C++ program where you implement a class with public and private members is an example of data abstraction. Consider the following example: #include <iostream> using namespace std; class Adder public: // constructor Adder(int i = 0) total = i; ; // interface to outside world void addnum(int number) total += number; // interface to outside world int gettotal() return total; ; private: // hidden data from outside world int total; int main( ) Adder a; a.addnum(10); a.addnum(20); a.addnum(30); cout << "Total " << a.gettotal() <<endl; return 0; When the above code is compiled and executed, it produces the following result: Total 60 Above class adds numbers together, and returns the sum. The public members addnum and gettotal are the interfaces to the outside world and a user needs to know them to use the class. The private member total is something that the user doesn't need to know about, but is needed for the class to operate properly. Spring 2018 CS3358 - Husain Gholoom Page 3

Benefits of ADT's. ADTs have several benefits: o o o o o o Simplicity: Client programmer does not have to be concerned with details that underlie the implementation of the ADT (eg keeping track of the front and back of a queue) Modularity - Reliability: Dividing a system into components or modules, each of which can be designed, implemented, tested, reasoned about, and reused separately from the rest of the system. Abstractions : Omitting or hiding low-level details with a simpler ideas Encapsulation: Building walls around a module (a hard shell or capsule) so that the module is responsible for its own internal behavior, and bugs in other parts of the system can t damage its integrity. Flexibility for client programmer: can choose from among several implementations of an ADT Example: array stack for efficient time and space Or linked stack for flexibility Independence: ADT programmer can change implementations of ADT without forcing client to change. Data Structures Again The term data structures is often extended to include both concrete AND logical descriptions of complicated data types. A list of data structures could include ADTs - arrays - linked lists - stacks - queues - vectors or lists Spring 2018 CS3358 - Husain Gholoom Page 4

ADTs and Program Design ADTs are an important part of bottom up program design In practice, programs are built using a combination of top down and bottom up approaches: o Top down: Decompose problem into subproblems, then decompose subproblems. Repeat until subproblems are simple Structure charts are a common design tool o Bottom up Design a set of tools and use them to build a solution the problem The tools are the values and operations of ADTs Designing ADTs is an essential part of bottom up design ADT Operations Categories Declare a variable of the type o (ie using a type defined in the package) Allocate a variable of the type o May be done by a declaration o Or may require a special operation (eg new or constructor-like call ) Operations on values (ie procedures and functions that have values of the type as parameters): o Query a property of the value or the status of a value or a component of a value o Modify a value (ie through an in/out parameter) o Combining two or more values and return a new value (of the same or different type) o Comparing two or more values o Convert a value to a string o Input/output of values Iterate through subcomponents Spring 2018 CS3358 - Husain Gholoom Page 5

Commonly used ADTs The purpose of many commonly used ADTs is to: - Store a collection of objects - Potentially organize the objects in a specific way - Provide potentially limited access to the objects These ADTs are often called - Containers - Collections - Container classes The ADT Basic Collections are : There are three basic collections. The basic collection is often called a bag. It stores objects with no ordering of the objects and no restrictions on them. Another unstructured collection is a set where repeated objects are not permitted: it holds at most one copy of each item. A set is often from a predefined universe. A collection where there is an ordering is often called a list. Specific examples include an array, a vector and a sequence. These have the same idea, but vary as to the methods they provide and the efficiency of those methods. Other Examples : - Stack and Queue - Tree - Map (or dictionary) Spring 2018 CS3358 - Husain Gholoom Page 6

A List ADT Values: ordered (1st, 2nd, etc) set of objects Operations: - constructor: creates an empty list - isempty: is the list empty - size: returns the number of elements - add an element to the end of the list - remove an element i from the list - return the element at position i - change the element at position (to another value) A Set ADT Values: collection of unique objects Operations: A Map ADT - constructor: creates an empty set - isempty: is the set empty - size: returns the number of elements - add an element to the set (if not there) - remove an element from the set (if it is there) - iselement(x): true if x is in the set - union: combine two sets into one A collection of unique keys and a collection of values where each key is associated with a single value. Keys have one type, values another. Operations may include: constructor: creates an empty map isempty: returns true if map has no key-value pairs size: returns the number of key-value pairs in the map get(k): returns value associated with key k (if any) put(k,v): associates value v with key k (adds a pair) keyset: returns a set of all the keys in the map Spring 2018 CS3358 - Husain Gholoom Page 7

A Bag (multi-set) ADT A bag is an ADT or abstract data type defines a way of storing data: it specifies only how the ADT can be used and says nothing about the implementation of the structure. The bag values are unordered collection of objects (may include duplicates) The Bag ADT might have: accessor methods such as size, count Occurrence, possibly an iterator (which steps through all the elements). modifier methods such as add, remove, and addall. A union method which combines two bags to produce a third. The Bag ADT Operations : Inside the bag are some elements, values, or numbers. When you first begin to use a bag, the bag will be empty ( called initial state ) Numbers may be inserted into a bag. The bag can hold many numbers We can even insert the same numbers more than once We may ask about the contents of the bag. We may remove a numbers from a bag. But we remove only one number at a time. We can determine how many numbers are in a bag. Spring 2018 CS3358 - Husain Gholoom Page 8

Summary of the Bag Operations: - constructor: creates an empty bag - isempty: is the bag empty - size: returns the number of elements - add an element to the bag - remove an element from the bag (if it is there) - removes all copies of an element from the bag - occurrences(x): how many times x is in the bag Implementing an ADT Interface : Implementation : - class declaration - prototypes for the operations - data members for the actual representation - ( *.h ) - function definitions for the operations - depends on data members (their representation) - ( *.cpp ) Spring 2018 CS3358 - Husain Gholoom Page 9

Example ADT: Bag Version - 1 bag.h class Bag public: Bag (); void insert(int element); void remove(int element); int occurrences(int element) const; bool isempty() const; int size() const; static const int CAPACITY = 20; ; private: int data[capacity]; int count; concrete representation Note : Member variables of a class can be made static by using the static keyword. Static member variables only exist once in a program regardless of how many class objects are defined! Spring 2018 CS3358 - Husain Gholoom Page 10

Example ADT: Bag Version - 1 bag.cpp #include "bag.h" #include <cassert> using namespace std; Bag::Bag () count = 0; void Bag::insert(int element) assert (count < CAPACITY); data[count] = element; count++; // what does this do? void Bag::remove(int element) int index = -1; for (int i=0; i<count && index==-1; i++) if (data[i]==element) index = i; if (index!=-1) data[index] = data[count-1]; count--; int Bag::occurrences(int element) const int occurrences=0; for (int i=0; i<count; i++) if (data[i]==element) occurrences++; return occurrences; bool Bag::isEmpty() const return (count==0); int Bag::size() const return count; Note : #include <cassert> is a header file in the standard library of the C programming. The macro implements an assertion, which can be used to verify assumptions made by the program and print a diagnostic message if this assumption is false. Spring 2018 CS3358 - Husain Gholoom Page 11

Bag - driver bagtest.cpp #include<iostream> #include "Bag.h" using namespace std; int main() Bag b; cout << "\nis empty " << b.isempty() << endl ; b.insert(4); b.insert(8); b.insert(4); cout << "is empty " << b.isempty() << endl << endl ; cout << "size " << b.size() << endl ; cout << "how many 4's: " << b.occurrences(4) << endl << endl; b.remove(4); cout << "removed a 4" << endl; cout << "size " << b.size() << endl; cout << "how many 4's: " << b.occurrences(4) << endl << endl; Bag c(b); cout << "copied to c" << endl; cout << "size " << c.size() << endl; cout << "how many 4's: " << c.occurrences(4) << endl << endl; b.insert(10); cout << "added 10 to b" << endl; cout << "b.size " << b.size() << endl; cout << "c.size " << c.size() << endl << endl; cout << "starting insert of 20 items" << endl; for (int i = 0; i < 20; i++) b.insert(33); cout << "inserted 20 more items into b" << endl; return 0; Spring 2018 CS3358 - Husain Gholoom Page 12

Bag driver : output output of running bagtest is empty 1 is empty 0 size 3 how many 4's: 2 removed a 4 size 2 how many 4's: 1 copied to c size 2 how many 4's: 1 added 10 to b b.size 3 c.size 2 starting insert of 20 items assertion "count < CAPACITY" failed: file "../bagimp.cpp", line 17, function: void Bag::insert(int) 0 [main] 3358-L5-Bag 4412 cygwin_exception::open_stackdumpfile: Dumping stack trace to 3358- L5-Bag.exe.stackdump One way to resolve is to increase the size of the array Bag Version 1 - Summary Implemented using a fixed size array When adding more elements than fit in the bag, the program exits. One Solution : increase the size of the array in bag.h Better Solution: - use a dynamically allocated array - when its capacity is reached, allocate a new, bigger array. Spring 2018 CS3358 - Husain Gholoom Page 13

Bag Version -2 : Using Dynamic Memory Allocation bag.h class Bag public: Bag (); Bag(const Bag &); // The big three (constructor destructor and operator= ) ~Bag(); void operator=(const Bag &); void insert(int element); void remove(int element); int occurrences(int element) const; bool isempty() const; int size() const; static const int INCREMENT = 20; ; private: int *data; //pointer to bag array // concrete representation int capacity; //size of the array int count; //number of elements currently in array Spring 2018 CS3358 - Husain Gholoom Page 14

Bag Version - 2 bag.cpp Bag::Bag () count = 0; capacity = INCREMENT; data = new int[capacity]; //copy constructor Bag::Bag(const Bag &rhs) data = new int[rhs.capacity]; //allocate new array capacity = rhs.capacity; //copy values count = rhs.count; for (int i=0; i<count; i++) data[i] = rhs.data[i]; //desctructor Bag::~Bag() delete [] data; void Bag::operator=(const Bag &rhs) if (data) delete [] data; //delete old array data = new int[rhs.capacity]; //allocate new array capacity = rhs.capacity; count = rhs.count; for (int i=0; i<count; i++) data[i] = rhs.data[i]; //copy values void Bag::insert(int element) //if count is at the capacity, resize if (count==capacity) capacity += INCREMENT; int *newdata = new int[capacity]; //new array for (int i=0; i<count; i++) //copy values newdata[i] = data[i]; delete [] data; //delete old array data = newdata; //make data point to new data[count] = element; //add new element count++; // no changes to remaining functions! Spring 2018 CS3358 - Husain Gholoom Page 15

bag driver : output version 2 output of running bagtest is empty 1 is empty 0 size 3 how many 4's: 2 removed a 4 size 2 how many 4's: 1 copied to c size 2 how many 4's: 1 added 10 to b b.size 3 c.size 2 starting insert of 20 items inserted 20 more items into b resizing succeeded! Spring 2018 CS3358 - Husain Gholoom Page 16

Bag Implementation Using Vector - Summary of the Operations: - constructor: creates an empty bag - drop : add a number to the bag - pick: erase an element from the bag - get_size : returns the number of elements - get_capacity : returns cap - display : display numbers - is_full : is the bag full - subtract : erase common numbers from 2 bags Spring 2018 CS3358 - Husain Gholoom Page 17

Vector Bag Implementation - bagvector.h #ifndef BAGVECTOR_H_ #define BAGVECTOR_H_ #include <iostream> #include <vector> using namespace std; class My_Bag private: const static int DS=5; vector<int> b; unsigned int cap; unsigned int size; public: My_Bag(); My_Bag(int); bool drop(int); bool pick(int); int get_size(); int get_capacity(); void display(); bool is_full(); bool subtract(const My_Bag&); ; bool My_Bag::subtract(const My_Bag& q) if (size==0 cap==0) return true; for (int i=0;i<q.b.size();i++) pick(q.b[i]); return true; Spring 2018 CS3358 - Husain Gholoom Page 18

Vector Bag Implementation ( cont. ) : My_Bag::My_Bag() cap=ds; size=0; My_Bag::My_Bag(int c) if (c<=0) cap=ds; else cap=c; size=0; bool My_Bag::drop(int item) if (size==cap) return false; b.push_back(item); ++size; return true; bool My_Bag::pick(int item) int index=-1; for (unsigned int i=0;i<size;i++) if (b[i]==item) index=i; b.erase(b.begin()+index); --size; return true; return false; int My_Bag::get_size() return size; Spring 2018 CS3358 - Husain Gholoom Page 19

Vector Bag Implementation ( cont. ) : int My_Bag::get_capacity() return cap; bool My_Bag::is_full() if (size==cap) return true; else return false; void My_Bag::display() cout << "Bag capacity: " << cap << endl; cout << "Current size: " << size << endl; for(unsigned int i=0;i<size;i++) cout << b[i] << ' '; cout << endl; #endif /* BAGVECTOR_H_ */ Spring 2018 CS3358 - Husain Gholoom Page 20

Vector Bag Implementation ( cont. ) : bagvectordriver.cpp #include <iostream> #include <vector> #include "bagvector.h" using namespace std; int main() My_Bag b1(5); b1.drop(10); b1.drop(10); b1.drop(20); b1.pick(10); b1.drop(20); b1.drop(30); b1.drop(10); b1.pick(20); b1.drop(-100); b1.drop(-100); b1.pick(10); b1.pick(10); b1.pick(30); b1.pick(-1009); b1.drop(20); b1.display(); cout << "==================\n"; Spring 2018 CS3358 - Husain Gholoom Page 21

bagvectordriver.cpp - ( continued ) My_Bag b2(10); b2.drop(20); b2.drop(20); b2.drop(30); b2.drop(78); b1.subtract(b2); b1.display(); cout << "==================\n"; b2.drop(-100); b2.drop(20); b2.subtract(b1); b2.display(); cout << "==================\n"; b2.drop(10); b1.subtract(b2); b1.display(); cout << "==================\n"; b1.drop(20); b2.subtract(b1); b2.display(); cout << "==================\n"; return 0; Spring 2018 CS3358 - Husain Gholoom Page 22

Sample Run Bag capacity: 5 Current size: 3 20-100 20 ================== Bag capacity: 5 Current size: 1-100 ================== Bag capacity: 10 Current size: 5 20 20 30 78 20 ================== Bag capacity: 5 Current size: 1-100 ================== Bag capacity: 10 Current size: 5 20 30 78 20 10 ================== Spring 2018 CS3358 - Husain Gholoom Page 23

ADT - Example -2 : Rolling a Pair of Dice Write a function that rolls a pair of dice until the sum of numbers rolled is a specific number. Also, calculate the number of times the dice are rolled to get the desired sum. Note that the smallest number in each die is 1 and the largest number is 6. So, the smallest sum of the numbers rolled is 2 and the largest sum of the numbers rolled is 12. Use the random number generator to randomly generate a number between 1 and 6 by using the following formula for both die1 and die2 :- die1 = rand() % 6 + 1; die2 = rand() % 6 + 1; sum = die1 + die2; Spring 2018 CS3358 - Husain Gholoom Page 24

Solution : Rolling a Pair of Dice die.h class die public: die(); //Default constructor //Sets the default number rolled by a die to 1 int roll(); //Function to roll a die. //This function uses a random number generator to randomly //generate a number between 1 and 6, and stores the number //in the instance variable num and returns the number. int getnum() const; //Function to return the number on the top face of the die. //Returns the value of the instance variable num. private: int num; ; Spring 2018 CS3358 - Husain Gholoom Page 25

die.cpp //Implementation File for the class clocktype #include <iostream> #include <cstdlib> #include <ctime> #include "die.h" using namespace std; die::die() num = 1; srand(time(0)); int die::roll() num = rand() % 6 + 1; return num; int die::getnum() const return num; Spring 2018 CS3358 - Husain Gholoom Page 26

diedriver.cpp //The user program that uses the class rolldie #include <iostream> #include "die.h" using namespace std; int main() die die1; die die2; int sum ; int rollcount = 0; cout << "die1: " << die1.getnum() << endl; cout << "die2: " << die2.getnum() << endl; sum = die1.getnum() + die2.getnum(); cout << "die1 + die2 = " << sum << endl; do cout << "After rolling die1: " << die1.roll() << endl; cout << "After rolling die2: " << die2.roll() << endl; cout << "The sum of the numbers rolled" << " by the dice is: " << die1.getnum() + die2.getnum() << endl; rollcount ++; while ( ( die1.getnum() + die2.getnum() )!= sum); cout << endl; cout << "The number of times the Dice was rolled = " << rollcount<<endl; return 0; //end main Spring 2018 CS3358 - Husain Gholoom Page 27

Sample Run die1: 1 die2: 1 die1 + die2 = 2 After rolling die1: 5 After rolling die2: 1 The sum of the numbers rolled by the dice is: 6 After rolling die1: 3 After rolling die2: 3 The sum of the numbers rolled by the dice is: 6 After rolling die1: 4 After rolling die2: 3 The sum of the numbers rolled by the dice is: 7 After rolling die1: 1 After rolling die2: 1 The sum of the numbers rolled by the dice is: 2 The number of times the Dice was rolled = 4 Spring 2018 CS3358 - Husain Gholoom Page 28

C++ STL: Standard Template Library A library of ADTs implemented in C++ Two categories of STL ADTs: o containers: classes that store a collection of data and impose some organization on it. It include sequence containers and associative containers. sequence containers: organize and access data sequentially, as in an array such as vector, deque, and list. associative containers: use keys to allow data elements to be quickly accessed. These include set, map ( map set of values to key must be unique ),and multimap ( same as map but it allows duplicate keys. o iterators: behave like pointers; a mechanism for accessing elements in a container the iterator is associated with. STL Iterators: iterators: Generalizations of pointers, used to access data stored in containers. They point to a certain value (or the past-the-end element). They may be dereferenced with *. Some types of iterators: - forward: uses ++ to advance to next element. - bidirectional: uses ++ and --. - random access: uses ++ and -- and uses [i] to jump to a specific element. Some vector member functions begin(): returns an iterator pointing to the vector s first element. end(): returns an iterator pointing to the vector s past the end element erase(iter): Removes from the vector either the single element the iterator argument is referring to. erase reduces the vector size by 1. Spring 2018 CS3358 - Husain Gholoom Page 29

Sample code using vectors and iterators #include <iostream> #include <vector> // Include the vector header using namespace std; int main() int count; // Loop counter vector<int> vect; // Define a vector of int object vector<int>::iterator iter; // Defines an iterator object // Use push_back to push values into the vector. for (count = 0; count < 10; count++) vect.push_back(count); // Step the iterator through the vector to display: cout << "The values in vector :\n\n" ; for (iter = vect.begin(); iter < vect.end(); iter++) cout << *iter << " "; // Step the iterator through the vector backwards. cout << "\n\nand here they are backwards:\n\n"; for (iter = vect.end() - 1; iter >= vect.begin(); --iter) cout << *iter << " "; // erase the 6th element vect.erase (vect.begin()+5); //advances 5 times cout << "\n\nvector contains:\n\n"; for (int i=0; i< vect.size(); i++) cout << ' ' << vect[i]; cout << endl; The values in vector : 0 1 2 3 4 5 6 7 8 9 and here they are backwards: 9 8 7 6 5 4 3 2 1 0 vector contains: 0 1 2 3 4 6 7 8 9 Spring 2018 CS3358 - Husain Gholoom Page 30

C++ Standard Template Library and Standard Library contain components such as : <array> <deque> New in C++11 and TR1. Provides the container class template std::array, a container for a fixed sized array. Provides the container class template std::deque, a double-ended queue. <forward_list> New in C++11 and TR1. Provides the container class template std::forward_list, a singly linked list. <list> <map> <queue> <stack> Provides the container class template std::list, a doubly linked list. Provides the container class templates std::map and std::multimap, sorted associative array and multimap. Provides the container adapter class std::queue, a single-ended queue, and std::priority_queue, a priority queue. Provides the container adapter class std::stack, a stack. <unordered_map> New in C++11 and TR1. Provides the container class template std::unordered_map and std::unordered_multimap, hash tables. <vector> Provides the container class template std::vector, a dynamic array. <algorithm> Provides definitions of many container algorithms such as sorting, searching. <iterator> Provides classes and templates for working with iterators. <string> <regex> Provides the C++ standard string classes and templates. New in C++11. Provides utilities for pattern matching strings using regular expressions. Spring 2018 CS3358 - Husain Gholoom Page 31

<fstream> Provides facilities for file-based input and output. See fstream. <iomanip> Provides facilities to manipulate output formatting, such as the base used when formatting integers and the precision of floating point values. <istream> Provides the template class std::istream and other supporting classes for input. <ostream> Provides the template class std::ostream and other supporting classes for output. <exception> Provides several types and functions related to exception handling, including std::exception, the base class of all exceptions thrown by the Standard Library. <thread> <mutex> New in C++11. Provide class and namespace for working with threads. New in C++11. 30.4-1. This section provides mechanisms for mutual exclusion: ( mutexes, locks, and call once. or exception) from a function that has run in the same thread or another thread. <complex> The header <complex> defines a class template, and numerous functions for representing and manipulating complex numbers. Spring 2018 CS3358 - Husain Gholoom Page 32

Exercise Give an ADT Temperature. The data includes high and low temperature values. Give an ADT Temperature. The data includes high and low temperature values for 10 days. Give an ADT Temperature. The data includes high and low temperature values for any number of days. Spring 2018 CS3358 - Husain Gholoom Page 33