lecture 3 - queues)

Upload: vicky-butt

Post on 08-Apr-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Lecture 3 - Queues)

    1/50

    ADT's and C++:ADT's and C++:A ReviewA Review

  • 8/7/2019 Lecture 3 - Queues)

    2/50

    ADT's, a reviewADT's, a review

    We've learned that it is often necessary toWe've learned that it is often necessary to

    develop new data types for our programming,develop new data types for our programming,

    and we develop ADT's.and we develop ADT's. In C++, an ADT is constructed using theIn C++, an ADT is constructed using the

    classclass construct.construct.

    Classes containClasses contain publicpublic andand privateprivate

    information, and can have sections so labeled.information, and can have sections so labeled.

  • 8/7/2019 Lecture 3 - Queues)

    3/50

    ADT's, a reviewADT's, a review

    TheThe publicpublic section contains the interface tosection contains the interface tothe ADT. It consists of a set of functionsthe ADT. It consists of a set of functionscalled methods.called methods.

    Two special types of methods exist and shouldTwo special types of methods exist and shouldalways be declared:always be declared: constructorsconstructors andanddestructorsdestructors..

    Other methods provide the basic ability toOther methods provide the basic ability toexamine and manipulate objects of the newexamine and manipulate objects of the newAbstract Data Type.Abstract Data Type.

  • 8/7/2019 Lecture 3 - Queues)

    4/50

    ADT's, a reviewADT's, a review

    TheThe privateprivate section contains the basis for thesection contains the basis for the

    implementation the ADT. It usually containsimplementation the ADT. It usually contains

    variables, constants and structures necessary forvariables, constants and structures necessary forthe implementation.the implementation.

    This private information is only visible to andThis private information is only visible to and

    accessible by the ADT itself; applications usingaccessible by the ADT itself; applications using

    the ADT can't see this information or refer to itthe ADT can't see this information or refer to it

    in any way.in any way.

  • 8/7/2019 Lecture 3 - Queues)

    5/50

    ADT's, a reviewADT's, a review

    The class definition is placed in a header fileThe class definition is placed in a header filewhich we call the ADT definition header.which we call the ADT definition header.

    The ADT definition header should be includedThe ADT definition header should be includedby any source or header file that needs to use theby any source or header file that needs to use theADT in question.ADT in question.

    The ADT definition header should also beThe ADT definition header should also be

    included by the ADT definition source file,included by the ADT definition source file,which implements all of the methods of thewhich implements all of the methods of theADT.ADT.

  • 8/7/2019 Lecture 3 - Queues)

    6/50

    ADT's, a reviewADT's, a review

    When creating a project that uses the ADT, theWhen creating a project that uses the ADT, the

    ADT definition header should be placed in theADT definition header should be placed in the

    list of project header files. The ADT definitionlist of project header files. The ADT definitionsource file should be placed in the list of projectsource file should be placed in the list of project

    source files.source files.

  • 8/7/2019 Lecture 3 - Queues)

    7/50

    ADT's, a reviewADT's, a review

    Putting all of this together, we arrive at thePutting all of this together, we arrive at the

    following two files: IntStack.h and IntStack.cpp.following two files: IntStack.h and IntStack.cpp.

  • 8/7/2019 Lecture 3 - Queues)

    8/50

    ADT's, a reviewADT's, a review// FILE: INTSTACK.H Stack of ints ADT definition

    #ifndef _INTSTACK#define _INTSTACK

    class IntStack{

    public:IntStack();~IntStack();bool is_empty()const;bool is_full()const;bool push(const int &value);bool pop(int &value);

    bool pop();int top()const;private:

    static const int MAX_SIZE = 10000;int top_index;int stack[MAX_SIZE];

    };

    #endif

  • 8/7/2019 Lecture 3 - Queues)

    9/50

    ADT's, a reviewADT's, a review

    // FILE: INTSTACK.CPP Stack of ints ADT implementation#include "IntStack.h"

    IntStack::IntStack(){

    top_index = -1;}

    IntStack::~IntStack(){

    }

    boolIntStack::is_empty()const

    {return (top_index == -1);

    }

    bool IntStack::is_full()const{

    return (top_index == MAX_SIZE-1);}

  • 8/7/2019 Lecture 3 - Queues)

    10/50

    ADT's, a reviewADT's, a reviewbool IntStack::push(const int &value){

    bool result = false;if (top_index < MAX_SIZE - 1){

    top_index++;stack[top_index]=value;result = true;

    }return result;

    }

    bool IntStack::pop()

    { bool result = false;if (top_index != -1){

    top_index--;result = true;

    }

    return result;}

  • 8/7/2019 Lecture 3 - Queues)

    11/50

    ADT's, a reviewADT's, a reviewbool IntStack::pop(int &value){

    bool result = false;if (top_index != -1){

    value = stack[top_index];top_index--;result = true;

    }

    return result;

    }

    int IntStack::top()const{

    return stack[top_index];}

  • 8/7/2019 Lecture 3 - Queues)

    12/50

    Introducing TemplatesIntroducing TemplatesLast week we created theLast week we created the IntStackIntStack

    ADT.ADT.Now, let's generalize it.Now, let's generalize it.

  • 8/7/2019 Lecture 3 - Queues)

    13/50

    ADT's, a reviewADT's, a review

    When using an ADT, the application refers onlyWhen using an ADT, the application refers only

    to the declaration of ADT objects and the use ofto the declaration of ADT objects and the use of

    the public methods on those objects. Thethe public methods on those objects. The

    private information can not be accessed.private information can not be accessed.

    You already know how this is done, since youYou already know how this is done, since you

    did your homework exercise for the week.did your homework exercise for the week.

  • 8/7/2019 Lecture 3 - Queues)

    14/50

    TemplatesTemplates

    The problem with the ADT just developed is that it isThe problem with the ADT just developed is that it isonly good for stacks of integers. If we wanted a stackonly good for stacks of integers. If we wanted a stackof student records, or a stack of floats, we're just out ofof student records, or a stack of floats, we're just out of

    luck.luck.

    We would have to develop a separate ADT for eachWe would have to develop a separate ADT for eachnewnew base typebase type. What a nuisance.. What a nuisance.

    Note that each new stack ADT would be basicallyNote that each new stack ADT would be basicallyidentical to the one we just saw, because a stack is aidentical to the one we just saw, because a stack is astack!!!!stack!!!!

  • 8/7/2019 Lecture 3 - Queues)

    15/50

    TemplatesTemplates

    To get around this, we will redefine the stack asTo get around this, we will redefine the stack asa template ADT.a template ADT.

    A template ADT is like a regular ADT, exceptA template ADT is like a regular ADT, exceptthat the base type (or other similar information)that the base type (or other similar information)becomes a parameter of the template.becomes a parameter of the template.

    But because of limitations of the C++ language,But because of limitations of the C++ language,

    we have to make some adjustments to howwe have to make some adjustments to howthings are put together.things are put together.

  • 8/7/2019 Lecture 3 - Queues)

    16/50

  • 8/7/2019 Lecture 3 - Queues)

    17/50

    TemplatesTemplates

    Each item that appears in the originalEach item that appears in the original .h.h andand.cpp.cpp file is given a template header.file is given a template header.

    The class definition is given a template header.The class definition is given a template header.

    Each method implementation is given aEach method implementation is given atemplate header.template header.

    Template header:Template header:

    templatetemplate

  • 8/7/2019 Lecture 3 - Queues)

    18/50

    TemplatesTemplatestemplatetemplate

    class Stackclass Stack{

    public:Stack();~Stack();

    bool is_empty()const;bool is_full()const;bool push(const BaseType&value);bool pop(BaseType&value);bool pop();Base

    Type

    top()

    co

    nst;

    private:static const int MAX_SIZE = 10000;int top_index;BaseTypestack[MAX_SIZE];

    };

    Template header: BaseType is a

    parameter of the template

    header,

    noteindent

    ation

    See how the BaseType is now a

    parameter

  • 8/7/2019 Lecture 3 - Queues)

    19/50

    TemplatesTemplates

    A similar thing is done with each method.A similar thing is done with each method.These method template definitions appear in theThese method template definitions appear in theheader file (unfortunately) because C++ can't doheader file (unfortunately) because C++ can't do

    it any other way.it any other way. For example, here's push:For example, here's push:

  • 8/7/2019 Lecture 3 - Queues)

    20/50

    TemplatesTemplatestemplatetemplate

    bool Stack::push(const BaseType&value){

    bool result = false;if (top_index < MAX_SIZE - 1){

    top_index++;stack[top_index]=value;result = true;

    }

    return result;

    }

    We do this for each of the methods and arriveat a file that looks like the following:

  • 8/7/2019 Lecture 3 - Queues)

    21/50

    TemplatesTemplates// FILE: STACK.H// FILE: STACK.H ADT template definition forstacksADT template definition forstacks

    #ifndef _STACK_TEMPLATE#ifndef _STACK_TEMPLATE#define _STACK_TEMPLATE#define _STACK_TEMPLATE

    templatetemplate class Stackclass Stack

    { public:Stack();~Stack();bool is_empty()const;bool is_full()const;bool push(const BaseType&value);

    bool pop(BaseType&value);bool pop();BaseTypetop()const;

    private:static const int MAX_SIZE = 10000;int top_index;BaseTypestack[MAX_SIZE];

    };

  • 8/7/2019 Lecture 3 - Queues)

    22/50

    TemplatesTemplatestemplate

    boolStack::is_empty()const{

    return (top_index == -1);}

    template bool Stack::is_full()const{

    retur

    n (top_index == MAX_SIZE-1);}

    Notice how in the member specifier we now show the ADT

    name with the parameter BaseType in angle brackets.

  • 8/7/2019 Lecture 3 - Queues)

    23/50

    TemplatesTemplatestemplate

    bool Stack::push(constBaseType&value)

    {

    bool result = false;if (top_index < MAX_SIZE - 1){

    top_index++;stack[top_index]=value;

    result = true;}

    return result;

    }

  • 8/7/2019 Lecture 3 - Queues)

    24/50

  • 8/7/2019 Lecture 3 - Queues)

    25/50

    TemplatesTemplatestemplate

    bool Stack::pop(BaseType&value){

    bool result = false;if

    (top_

    ind

    ex!= -1

    )

    {

    value = stack[top_index];top_index--;result = true;

    }return result;

    }

  • 8/7/2019 Lecture 3 - Queues)

    26/50

    TemplatesTemplates

    template BaseType Stack::top()const{

    return stack[top_index];}

    #endif

  • 8/7/2019 Lecture 3 - Queues)

    27/50

    Using TemplatesUsing Templates

    Let's look at how we can use a template in anLet's look at how we can use a template in anapplication.application.

    The example that follows is for demonstrationThe example that follows is for demonstrationof syntax only.of syntax only.

    You would put the source file that follows intoYou would put the source file that follows intoyour projects list of source files and stack.h intoyour projects list of source files and stack.h intoyour list of header files.your list of header files.

  • 8/7/2019 Lecture 3 - Queues)

    28/50

    Using TemplatesUsing Templates// Samplesource fileusingthe Stacktemplate ADT#include using namespace std;#include "stack.h"

    int main()

    {Stacks;int value;

    while (cin>>value){

    if (value>0)cout

  • 8/7/2019 Lecture 3 - Queues)

    29/50

    HomeworkHomework

    Write a C++ program that reads a series ofWrite a C++ program that reads a series ofintegers from cin and determines whether it is aintegers from cin and determines whether it is azerozero--marked palindromemarked palindrome..

    AA zerozero--marked palindromemarked palindrome consists of a seriesconsists of a seriesof integer values, only one of which has theof integer values, only one of which has thevalue zero. If the values are the same, lookingvalue zero. If the values are the same, lookingbackwards and forwards, with a zero in thebackwards and forwards, with a zero in the

    middle, the input is a zeromiddle, the input is a zero--marked palindrome.marked palindrome. For example: 5 10 40 20 0 20 40 10 5 is a zeroFor example: 5 10 40 20 0 20 40 10 5 is a zero--

    marked palindrome.marked palindrome.

    Use the template ADT inUse the template ADT in stack.hstack.h to do theto do the

    checking.checking.

  • 8/7/2019 Lecture 3 - Queues)

    30/50

    QueuesQueues

    A queue isA queue is homogeneoushomogeneous,, firstfirst--in,in, firstfirst--outout(FIFO)(FIFO)

    structure.structure.

    HomogeneousHomogeneous means that all the values stored in ameans that all the values stored in a

    queue are of the same typequeue are of the same type

    FirstFirst--in,in, firstfirst--outoutmeans that the first value insertedmeans that the first value inserted

    into the queue would be the first one we would beinto the queue would be the first one we would be

    able to extractable to extract

    We insert new values at theWe insert new values at the tailtailof the queue andof the queue and

    remove values from theremove values from the headheadof the queue.of the queue.

  • 8/7/2019 Lecture 3 - Queues)

    31/50

    QueuesQueues

    AnAn emptyempty queue is one that contains no values.queue is one that contains no values.We cannot remove from an empty queue.We cannot remove from an empty queue.

    In some implementations, it is necessary toIn some implementations, it is necessary to

    define adefine a fullfullqueue as one that has no morequeue as one that has no moreroom for any more values. We cannot insertroom for any more values. We cannot insertinto a full queue.into a full queue.

    TheThecurrentcurrentvalue in a queue is the first of thevalue in a queue is the first of thevalues in the queue that we inserted.values in the queue that we inserted.

  • 8/7/2019 Lecture 3 - Queues)

    32/50

    QueuesQueues

    template class Queue

    {

    public:Queue();

    ~Queue();

    bool is_empty()const;bool is_full()const;bool insert(const Type&value);bool remove(Type &value);

    bool remove();Typecurrent()const;// valueathead

    // of queuefriend ostream&operator

  • 8/7/2019 Lecture 3 - Queues)

    33/50

    friendfriend functionsfunctions

    Introducing friendfunctions

    Sometimes we have functions that are not actual

    methods that we would like to define for a class. For

    example, suppose we want to overload the operator

  • 8/7/2019 Lecture 3 - Queues)

    34/50

    friendfriend functionsfunctions

    But

  • 8/7/2019 Lecture 3 - Queues)

    35/50

    friendfriend functionsfunctions

    For example, suppose we decided (incorrectly) that we

    would like to supply a friend function that returns the

    size of a queue.

    Let's call it size_of

    friendint size_of (Queue)

    Usage: count = size_of(q);

  • 8/7/2019 Lecture 3 - Queues)

    36/50

    operator overloadingoperator overloading

    We also introduce the concept of operator overloading.

    It's like function overloading, but we redefine a C++

    operator instead.

    We can re-define any existing C++ operator to work on

    new kinds of objects. Merely declare:

    MyType&operator +(const MyType&operand)

    instead of

    MyType&add_operand(const MyType&operand)

  • 8/7/2019 Lecture 3 - Queues)

    37/50

    operator overloadingoperator overloading

    and call bymy_number = x+y;

    instead of

    my_number = x.add_operand(y);

  • 8/7/2019 Lecture 3 - Queues)

    38/50

    QueuesQueues

    As with stacks, there are many ways toAs with stacks, there are many ways to

    implement a queue: e.g.implement a queue: e.g. -- arrays, Vectors,arrays, Vectors,

    linked lists.linked lists.

    Array implementation: the traveling problem.Array implementation: the traveling problem.

    Unlike stacks, which have one movable endUnlike stacks, which have one movable end

    (the top), queues have two movable ends (the(the top), queues have two movable ends (the

    head and the tail)head and the tail)

  • 8/7/2019 Lecture 3 - Queues)

    39/50

    Array implementation ofQueuesArray implementation ofQueues

    private:static const int MAX_SIZE = 100;int head,tail;int size;

    Type queue[MAX_SIZE];

    }

    We maintain a size this time, for convenience (as we will see later)

    Insertion is done by: tail++; queue[tail] = value;

    removal is done by: value = queue[head];head++;

    What happens when we alternately insert and remove?

  • 8/7/2019 Lecture 3 - Queues)

    40/50

    Array implementation ofQueuesArray implementation ofQueues

    0

    1

    2

    3

    n-4

    n-3

    n-2

    n-1

    head

    tail

  • 8/7/2019 Lecture 3 - Queues)

    41/50

    Array implementation ofQueuesArray implementation ofQueues

    This is known asThis is known as driftdrift. The head and tail have. The head and tail havea tendency to move down the array and taila tendency to move down the array and tailreaches the end of the array, not allowing anyreaches the end of the array, not allowing any

    more insertions even though theres room inmore insertions even though theres room inthe area before the head.the area before the head.

    Solution:Solution: Circular storageCircular storage. Imagine that the. Imagine that thetwo ends of the array are wrapped around sotwo ends of the array are wrapped around sothey meet. The next location after the lastthey meet. The next location after the lastone is the first one!!!one is the first one!!!

  • 8/7/2019 Lecture 3 - Queues)

    42/50

    Array implementation ofQueuesArray implementation ofQueues

    Circular StorageCircular Storage

    0

    1

    n-1

    2

    3

    4

    n-2

  • 8/7/2019 Lecture 3 - Queues)

    43/50

    Array implementation ofQueuesArray implementation ofQueuestemplate

    Queue::Queue(){

    size = 0;head = 0;tail = -1;

    }

    template Queue::~Queue(){

    }

  • 8/7/2019 Lecture 3 - Queues)

    44/50

    Array implementation ofQueuesArray implementation ofQueuestemplate

    bool Queue::is_empty()const{

    return size == 0;}

    template boolQueue::is_full()const{

    return size == MAX_SIZE;}

  • 8/7/2019 Lecture 3 - Queues)

    45/50

    Array implementation ofQueuesArray implementation ofQueuestemplate

    bool Queue::insert(const Type&value){

    bool success = !is_full();

    if (success)

    {size++;

    tail = (tail+ 1) % MAX_SIZE;queue[tail] = value;

    }

    return success;

    }

  • 8/7/2019 Lecture 3 - Queues)

    46/50

    Array implementation ofQueuesArray implementation ofQueuestemplate

    bool Queue::remove(Type&value){

    bool success = !is_empty();

    if (success)

    {size--;value = queue[head];head = (head+ 1) % MAX_SIZE;

    }

    return success;

    }

  • 8/7/2019 Lecture 3 - Queues)

    47/50

    Array implementation ofQueuesArray implementation ofQueuestemplate

    bool Queue::remove(){

    bool success = !is_empty();

    if (success)

    { size--;head = (head+ 1) % MAX_SIZE;

    }

    return success;

    }

  • 8/7/2019 Lecture 3 - Queues)

    48/50

    Array implementation ofQueuesArray implementation ofQueuestemplate

    BaseTypeQueue::current()const{

    return queue[head];}

  • 8/7/2019 Lecture 3 - Queues)

    49/50

  • 8/7/2019 Lecture 3 - Queues)

    50/50

    HomeworkHomework

    Write a C++ program that reads a series ofWrite a C++ program that reads a series ofnumbers fromnumbers from cincin. Upon completion, write. Upon completion, write

    the nonthe non--negative values tonegative values to coutcout in the reversein the reverse

    order from how they came in. Then write theorder from how they came in. Then write the

    negative values in the same order as they camenegative values in the same order as they came

    in.in.