Homework 2
CS 300, Parallel and Distributed Computing (PDC)
- Homework 2 Due 10/5/2018
-
-
STL queue container
-
[c]
The Standard Template Library (STL) is a collection of common data structures and algorithms that are predefined for C++.
-
The STL containers are classes that implement data structures including
vector(a dynamically resizable array),list(a doubly linked list),queue(a first-in first-out queue), andmap(an ordered collection of key-value pairs). -
STL iterators are objects for traversing (moving along) containers, whether in a forward direction, both forward or backward, or for random access.
-
STL algorithms implement common algorithms for containers such as
sort,binary_search(for searching an ordered container),random_shuffle, andmax. -
STL functionals (also called functions) are objects that behave as functions, for comparing, combining, or operating on elements of one or two containers, such as
negate,equal_to,plus, anddivides.
The STL uses C++ templates in order to make STL containers versatile (and hence also their iterators, algorithms, and functionals), so that elements of an STL container can have arbitrary types. Templates make it possible to specify a type as a parameter. For example, in the Software Design course, we implemented
IntArrayandFloatArray, two classes that were identical except replacing the typeintbyfloat. A templated definitiontemplate <type T> class Array { protected: T *vec; int size; ... }would define a templated classArraysuch that the type nameArray<int>is equivalent to theIntArrayclass, andArray<float>is equivalent to theFloatArrayclass. Likewise, the algorithmsortis a templated function that sorts a range within a container (where the endpoints of that range are specified as iterators).
We will begin exercises with the STL by using the STL
queuecontainer to create partial code for a simulation of the checkout area of a store. That simulation will usequeueobjects to represent checkout registers, where each element of a Registerqueueis an integer representing the number of items in a single store cart. Over time, new carts are added to the end of thatqueue, and the oldest cart in thatqueueis removed once all of that cart's items have been processed.Although we are using a store checkout area as an application of
queues, similar code could be used for other uses ofqueues. For example, instead of representing a cash register, aqueuemight represent a line of voters at a polling station, a segment of a freeway in a traffic simulation, or a collection of chemicals awaiting a reaction.
DO THIS: Implement a file
~/PDC/hw2/Register.hthat implements a classRegistersatisfying this Doxygen spec, and build an executable usingRegister.h, checkout.cpp, and Makefile that simulates a store's checkout area.Suggestions:
-
On a Link machine, create a subdirectory
PDC/hw2for your work on this homework, and copy the filescheckout*andMakefilefrom/usr/local/cs/cs300/hwto yourhw2subdirectory.% mkdir ~/PDC/hw2 % cd !$ % cp /usr/local/cs/cs300/hw/{checkout*,Makefile} .(Don't overlook the final dot in thatcpcommand.) Here the shell notation!$refers to the final command-line argument in the previous command, which is~/PDC/hw2in this case, and the notation/usr/local/cs/cs300/hw/{checkout*,Makefile}(no spaces around commas) is a shell notation for/usr/local/cs/cs300/hw/checkout* /usr/local/cs/cs300/hw/Makefile
-
The copied file
checkoutis an executable that results from a solution to this problem, and the text filecheckout.outconsists of the first 30 lines of output from a run ofcheckout, as an illustration. You can runcheckoutas follows:% ./checkout | more
Piping output tomore(orless) isn't required, but displaying the output one page at a time prevents the simulation from scrolling through thousands of iterations before you can examine them. -
Your task is to create a file
Register.hthat implements a classRegisterthat is a FIFO (first-in, first-out) queue. A queue data structure contains zero or more objects (or values) of the same type, and supports operations to add a new element to the "end of the line," remove an element from the "beginning of the line," determine whether any elements exist in that queue, etc. -
Implement the
Registerclass that satisfies this spec.Registershould be a subclass of the STL containerqueue<int>, a queue ofintvalues. Each integer queue element will represent a count of items to be purchased in one shopping cart, among thatRegister's waiting line of carts.Note: In Software Design we always specified
publicaccess for superclasses, e.g.,class OwnedDog : public Dog { ... };This indicates a limit for the most accessible members inherited from that superclassDog. But useprivateaccess for the superclassqueue<int>ofRegister.class Register : private queue<int> { ... };The reasons for this access choice are technical: destructors of STL containers are notvirtual, so applications involving multiple inheritance or deallocating through a pointer may be unsafe. The standard advice is not to use STL containers as superclasses, and to make containers available to algorithms using iterators. But we suggest simplifying this early assignment by using C++privateinheritance, which prevents the superclassqueue<int>from factoring in multiple inheritance, and prevents unsafe deallocation of aRegisterthrough a pointer to aqueue<int>superclass object.Terminology-
base class: C++ term for a superclass.
-
derived class: C++ term for a subclass
-
-
The documentation for the STL
queuecontainer indicates the header file required to usequeues near the upper right hand corner. Thus, be sure to enter#include <queue>
near the top of your fileRegister.h. Also, you must usestd::queueto refer to an STLqueueunless you enter a directive such asusing namespace std;
-
The spec for
Registerwas generated by the Doxygen system (to be described later). Here are some comments about interpreting that spec.-
The inheritance diagram section indicates that
Registershould beprivatesubclass ofstd::queue<int>, i.e., "derived from the base classstd::queue<int>". The red dotted arrow in that inheritance diagram indicatesprivateaccess, which means thatqueue<int>members (e.g., methods) are accessible within the scopeRegister::but not outside of that scope. A green dotted arrow indicatesprotectedaccess to base-class members, and a solid blue arrow indicatespublicaccess. -
The public member functions section lists the methods for
Register. Clicking on the name of a method (or scrolling down the web page) provides details of the spec for each method.Terminology-
member function: C++ term for a method, operator, constructor, or destructor in a class
-
data member: C++ term for a state variable.
-
-
The Attribute sections list the state variables, i.e., data members, expected for the
Registerclass. Clicking on the name of a data member (or scrolling down) provides documentation of those members.These attribute sections show one per-instance state variable (data member) named
remaining, and one class variable (static data member) calledtransact_time. -
The detailed description of the
Registerclass begins after these initial lists.-
The detailed description section gives an overview of the class.
-
The member function documentation provides specs for each of the desired methods.
-
The "member data documentation" section describes each data member.
-
-
Here is an explanation of some of the state variables and methods:
-
This simulation of a store checkout area proceeds in iterations that each represent the passage of a certain amount of time.
-
Between iterations, an individual
Registermay have processed part, but not all, of the items in it's first cart. The data memberremainingindicates how much more processing is (still) needed for the first shopping cart in in the queue for a particularRegister. -
The
Register::push()method calls thequeue<int>::push()method to add an integer (representing a cart) to the queue. But if wepush()a cart onto to an empty queue, then the data memberremainingalso needs to be assigned the work needed to process that whole cart. -
Time is measured in this simulation according to the number of items scanned at registers: one unit of time corresponds to scanning one item. The (static) data member
transactTimeis the amount of time added to each cart, representing the time to pay for scanned item and for the next cart to arrive for scanning. (ThustransactTime+ i should be assigned to the data memberremainingwhen a new cart containing i items arrives at the beginning of the queue. -
Pseudocode is provided for the member function
advanceTime(), which is at the heart of the simulation. -
Note that we don't need to define a default constructor, copy constuctor, destructor, or assignment operator for
Registersince that class has no dynamically allocated state variables.
-
-
-
Comments on the main program for the simulation
checkout.cpp:-
The program defines a class
CheckoutAreathat contains an array ofRegister, and definesmain()to use aCheckoutAreaobject to carry out the simulation. -
The
CheckoutAreaclass definition defines a default constructor, copy constructor, destructor, and assignment operator, since that class dynamically allocates memory (namely, the arrayreg[]).CheckoutAreaalso defines an index operator for convenient access to individualRegisters in the array. -
The constructor
CheckoutArea(int sz = DFLT_REGISTERS) { ... }provides a default valueDFLT_REGISTERS(defined earlier), so that constructor may be used with 0 or 1 argument. It thus serves as the default constructor forCheckoutAreawhen no argument is provided. -
The member function
CheckoutArea::advanceTime()primarily calls theadvanceTime()method for eachRegisterin its array. -
The main program uses
rand()to generate a random number of carts per simulation iteration, determine a random number of items per cart, and assign each cart to a randomly chosenRegisterwithin aCheckoutAreaarray. Then, it advances time byitemsPerIterunits, and repeats. -
The code provides for no exit from the simulation loop. (You will have to stop the program, for example, by entering CTRL-C.)
-
-
To compile and run your program, enter the shell commands
% make checkout % ./checkout | more
You can visually compare your first page of output tocheckout.out. To compare character-by-character, enter the command% ./checkout | head -30 | diff - checkout.out
Here,head -30copies the first 30 lines (only) of standard input to standard output, anddiff - checkout.outcompares standard input to the filecheckout.out, printing any differences it finds. -
If you run the program without piping its output to
more,head, etc., then you will have to enter CTRL-C to stop it.
-
-
[c]
Make a
commitof your code:link% git add checkout.cpp Makefile Register.h link% git commit -m "hw2: Implement Register queue"
-
-
Submitting this homework
All of your code for this assignment should already be contained in
commits. Modify the most recentcommitmessage to indicate that you are submitting the completed assignment.link% git commit --amend
Add the following to the latestcommitmessage.hw2: completeIf your assignment is not complete, indicate your progress instead, e.g.,hw2: items 1-5 complete, item 6 partialYou can make later commits to submit updates.Finally,
pull/pushyourcommits in the usual way.link% git pull origin master link% git push origin master
Files:
checkout.cpp Makefile Register.h
-