I am to implement a Circular Array Queue But I a having logical errors and I am not getting the correct result. I need help implementing bool dequeue() in ArrayQueueP4.h. I doubt if it is correct.
.
I have tried different solutions as well as search through previous questions on stack overflow and online yet it did not give me any ideas on what I am looking for
#ifndef ARRAY_QUEUE_P4_
#define ARRAY_QUEUE_P4_
#include "QueueInterface.h"
#include "PrecondViolatedExcept.h"
template<class ItemType>
class ArrayQueueP4 : public QueueInterface<ItemType>
{
private:
static const int DEFAULT_CAPACITY = 50;
ItemType items[DEFAULT_CAPACITY + 1]; // Array of queue items
int front; // Index to front of queue
int back; // Index to back of queue
public:
ArrayQueueP4() : front(DEFAULT_CAPACITY),
back(DEFAULT_CAPACITY) {};
// Copy constructor and destructor supplied by compiler
bool isEmpty() const;
bool enqueue(const ItemType& newEntry);
bool dequeue();
/** #throw PrecondViolatedExcept if queue is empty. */
ItemType peekFront() const;
};
ArrayQueueP4.h is the header file for ArrayQueueP4.cpp
#include "ArrayQueueP4.h";
#include "PrecondViolatedExcept.h";
using namespace std;
template <class ItemType>
bool ArrayQueueP4 <ItemType>::isEmpty() const {
return (front == back);
}
template <class ItemType>
bool ArrayQueueP4 <ItemType>::enqueue(const ItemType& newEntry) {
if (!isEmpty())
back = (back + 1) % DEFAULT_CAPACITY;
items[back] = newEntry;
back++;
return true;
}
template<class ItemType>
bool ArrayQueueP4 <ItemType> ::dequeue() {
bool result = false;
if (!isEmpty()) {
front = (front + 1) % DEFAULT_CAPACITY;
front--;
result = true;
}
return result;
}
template<class ItemType>
ItemType ArrayQueueP4<ItemType>::peekFront() const {
if (isEmpty())
throw PrecondViolatedExcept("peekFront() called with an empty queue.");
else
return items[front];
}
HERE is my main file main.cpp to test my code
#include <iostream>
#include "ArrayQueueP4.cpp";
using namespace std;
int main() {
ArrayQueueP4<int> AP;
AP.enqueue(1);
AP.enqueue(2);
AP.enqueue(3);
/*LinkedQueueP1<int> LP;
LP.enqueue(1);
LP.enqueue(2);*/
cout << "PEEK FRONT: " << AP.peekFront();
//cout << "PEEK FRONT: " << LP.peekFront();
system("pause");
return 0;
}
Based on my main program file, the output supposed to now 1 when I call the enqueue function. But instead of getting 2 as my answer, I am getting -858993460 as my result when I delete the first item using dequeue(). I do not know if that is how Queues behave but isn't the second number supposed to be the next first item in line when I delete the first number?
According to your description, your front and back defines a range, such that front is the first element available in the queue, and back is the "pass-the-end" index. Then according to those definition the code should look like this:
template <class ItemType>
bool ArrayQueueP4 <ItemType>::enqueue(const ItemType& newEntry) {
// Check if queue is full
if ((back + 1) % (DEFAULT_CAPACITY + 1) == front) return false;
// Append element at one-pass-end position
items[back] = newEntry;
// Update the one-pass-end index (back)
// All your modulo operation should be dealing with DEFAULT_CAPACITY + 1
// because that is the size of your array
back = (back + 1) % (DEFAULT_CAPACITY + 1);
return true;
}
template<class ItemType>
bool ArrayQueueP4 <ItemType> ::dequeue() {
// Dequeue fail if the queue is empty
if (isEmpty()) return false;
front = (front + 1) % (DEFAULT_CAPACITY + 1);
return true;
}
Also, as a reminder, your code does not take resource management in to account (although it works for most types and doesn't seem to make any mistakes). When an item is dequeued, it's corresponding resources should be released. As an exercise, think about the scenario where ItemType is std::unique_ptr (or std::shared_ptr). This is probably not what your teacher wants, but it is a good practice.
Related
I'm working on an assignment and the goal is to make a module that will assist in representing a priority queue displaying each 'item' and it's appropriate 'priority value'. I'm not asking anybody to do my "homework" for me as stated in my previous post, I'm simply asking for help understanding where I am going wrong with my insert and insertCell functions that gives me errors. Any advice/tips would be very helpful in solving my problem.
//Beginning of Code
//File: pqueue.cpp
//Module pqueue.cpp provides priority queues that include items and their
//priority types. It tests for empty queues, can insert priority queues that
//include a new item with a new priority, can remove priority queues and/or
//items with their priorities, and can print each item along with its priority
//to the standard output.
//
//
#include <cstdio>
#include "pqueue.h"
#include <cstdlib>
using namespace std;
//An object of type PQCell represents a cell in a linked list.
//
//PQCell has three field.
//
//item- the particular item that is entered
//priority- the priority that an item has
//nextList- a pointer to the next cell in the list
struct PQCell
{
ItemType item;
PriorityType priority;
PQCell *nextItem;
PQCell(ItemType a, PriorityType b, PQCell* nextCell)
{
item = a;
priority = b;
nextItem = nextCell;
}
};
//Function isEmpty returns true if the queue is empty and false if it is not.
bool isEmpty(const PriorityQueue& q)
{
if(q.cells == NULL)
{
return false;
}
return true;
}
//Function insertCell inserts item x with priority p into a linked list 'L'.
void insertCell(PQCell*& L, ItemType x, PriorityType p)
{
if(L==NULL || L -> priority > p)
{
L = new PQCell(x, p, L);
}
else
{
insertCell(L -> nextItem, x,p);
}
}
//Function insert inserts item x with priority p into a priority queue 'q'.
void insert(PriorityQueue& q, ItemType x, PriorityType p)
{
insertCell(q, x, p);
}
//Function printPriorityQueue prints a representation of the priority queue
//including each value, x, and it's priority type, y, respectively.
void printPriorityQueue(const PriorityQueue& q, ItemPrinter printItem,
PriorityPrinter printPriority)
{
PQCell* pointer = q.cells;
while(pointer != NULL)
{
printf("Item = ");
(printItem)(pointer->item);
printf(" Priority = ");
(printPriority)(pointer->priority);
printf("\n");
pointer = pointer -> nextItem;
}
}
//Function remove removes the item with the smallest priority. It also stores
//the item and it's priority into x and p, respectively.
void remove(PriorityQueue& q, ItemType& x, PriorityType& p)
{
if(q.cells != NULL)
{
PQCell *pointer = q.cells;
q.cells = q.cells -> nextItem;
x = pointer -> item;
p = pointer -> priority;
delete [] pointer;
}
else
{
printf("Q is empty");
exit(1);
}
}
//File: pqueue.h
typedef const char* ItemType;
typedef double PriorityType;
struct PQCell;
typedef void (*ItemPrinter)(ItemType);
typedef void (*PriorityPrinter)(PriorityType);
struct PriorityQueue
{
PQCell* cells;
PriorityQueue()
{
cells = NULL;
}
};
bool isEmpty(const PriorityQueue& q);
void insert(PriorityQueue& q, ItemType x, PriorityType p);
void printPriorityQueue(const PriorityQueue& q, ItemPrinter printItem,
PriorityPrinter printPriority);
void remove(PriorityQueue& q, ItemType& x, PriorityType& p);
The main problem I'm having is like I said, the insert and insertCell functions. I keep receiving the errors:
pqueue.cpp: In function void insert(PriorityQueue*&, ItemType, PriorityType):
pqueue.cpp:70:20: error: invalid initialization of reference of type PQCell*& from expression of type PriorityQueue*
insertCell(q, x, p);
pqueue.cpp:54:6: error: in passing argument 1 of void insertCell(PQCell*&, ItemType, PriorityType)
void insertCell(PQCell*& L, ItemType x, PriorityType p)
Again, any help would be great, thanks.
The main problem (the one that's causing the invalid initialization error) is that you're passing a PriorityQueue& into a function that's expecting a PQCell*&:
//Function insert inserts item x with priority p into a priority queue 'q'.
void insert(PriorityQueue& q, ItemType x, PriorityType p)
{
// Wrong.
//insertCell(q, x, p);
// You probably meant to do this:
insertCell(q.cells, x, p);
}
I also noticed that your isEmpty logic seems to be backwards:
//Function isEmpty returns true if the queue is empty and false if it is not.
bool isEmpty(const PriorityQueue& q)
{
if(q.cells == NULL)
{
return false;
}
return true;
}
You're returning false if q.cells == NULL, when you probably meant to be returning true in that case, and false otherwise.
In the attached code, I can't get beyond the error function template has already been defined for every function in my class file.
I have been all through it and can't figure out where the functions are already defined anywhere. Note that this code was assembled while going through the chapters of a book, just trying to create functional code to start off with.
BagInterface.h:
/** #file BagInterface.h */
#ifndef BAG_INTERFACE_
#define BAG_INTERFACE_
#include <vector>
using std::vector;
template<class ItemType>
class BagInterface
{
public:
/** Gets the current number of entries in this bag.
#return The integer number of entries currently in the bag. */
virtual int getCurrentSize() const = 0;
/** See whether this bag is empty.
#return True if the bag is empty, or false if not. */
virtual bool isEmpty() const = 0;
/** Adds a new entry to this bag.
#post If successful, newEntry is stored in the bag and
the count of items in the bag has increased by 1.
#param newEntry The object to be addedd as a new entry.
#return True if addition was successful, or false if not. */
virtual bool add(const ItemType& newEntry) = 0;
/** Removes one occurrence of a given entry from this bag.
if possible.
#post If successful, anEntry has been removed from the bag
and the count of items in the bag has decreased by 1.
#param anEntry The entry to be removed.
#return True if removal was successful, or false if not. */
virtual bool remove(const ItemType& anEntry) = 0;
/** Removes all entries from this bag.
#post Bag contains no items, and the count of the items is 0. */
virtual void clear() = 0;
/** Counts the number of times a given entry appears in this bag.
#param anEntry The entry to be counted.
#return The number of times anEntry appears in the bag. */
virtual int getFrequencyOf(const ItemType& anEntry) const = 0;
/** Tests whether this bag contains a given entry.
#param anEntry The entry top locate.
#return True if bag contains anEntry, or False otherwise. */
virtual bool contains(const ItemType& anEntry) const = 0;
/** Empties and then fills a given vector with all entries that
are in this bag.
#return A vector containing copies of all the entries in this bag. */
virtual vector<ItemType> toVector() const = 0;
/** Destroys this bag and frees its assigned memory. */
virtual ~BagInterface() { }
}; // end BagInterface
#endif
ArrayBag.h:
/** #file ArrayBag.h */
#ifndef ARRAY_BAG_
#define ARRAY_BAG_
#include "BagInterface.h"
template<class ItemType>
class ArrayBag : public BagInterface<ItemType>
{
private:
static const int DEFAULT_CAPACITY = 6;
ItemType items[DEFAULT_CAPACITY];
int itemCount;
int maxItems;
int getIndexOf(const ItemType& target, int searchIndex) const;
int countFrequency(const ItemType& target, int searchIndex) const;
public:
ArrayBag();
int getCurrentSize() const;
bool isEmpty() const;
bool add(const ItemType& newEntry);
bool remove(const ItemType& anEntry);
void clear();
bool contains(const ItemType& anEntry) const;
int getFrequencyOf(const ItemType& anEntry) const;
vector<ItemType> toVector() const;
};
#include "ArrayBag.cpp"
#endif
ArrayBag.cpp:
#include "ArrayBag.h"
template<class ItemType>
ArrayBag<ItemType>::ArrayBag() : itemCount(0), maxItems(DEFAULT_CAPACITY)
{
}
template<class ItemType>
int ArrayBag<ItemType>::getIndexOf(const ItemType& target, int searchIndex) const
{
int result = -1;
if (searchIndex < itemCount)
{
if (items[searchIndex] == target)
{
result = searchIndex;
}
else
{
result = getIndexOf(target, searchIndex + 1);
}
}
return result;
}
template<class ItemType>
bool ArrayBag<ItemType>::add(const ItemType& newEntry)
{
bool hasRoomToAdd = (itemCount < maxItems);
if (hasRoomToAdd)
{
items[itemCount] = newEntry;
itemCount++;
}
return hasRoomToAdd;
}
template<class ItemType>
vector<ItemType> ArrayBag<ItemType>::toVector() const
{
vector<ItemType> bagContents;
for (int i = 0; i < itemCount; i++)
bagContents.push_back(items[i]);
return bagContents;
}
template<class ItemType>
int ArrayBag<ItemType>::getCurrentSize() const
{
return itemCount;
}
template<class ItemType>
bool ArrayBag<ItemType>::isEmpty() const
{
return itemCount == 0;
}
template<class ItemType>
bool ArrayBag<ItemType>::remove(const ItemType& anEntry)
{
int locatedIndex = getIndexOf(anEntry, 0);
bool canRemoveItem = !isEmpty() && (locatedIndex > 1);
if (canRemoveItem)
{
itemCount--;
items[locatedIndex] = items[itemCount];
}
return canRemoveItem;
}
template<class ItemType>
void ArrayBag<ItemType>::clear()
{
itemCount = 0;
}
template<class ItemType>
int ArrayBag<ItemType>::getFrequencyOf(const ItemType& anEntry) const
{
return countFrequency(anEntry, 0);
}
template<class ItemType>
int ArrayBag<ItemType>::countFrequency(const ItemType& target, int searchIndex) const
{
int frequency = 0;
if (searchIndex < itemCount)
{
if (items[searchIndex] == target)
{
frequency = 1 + countFrequency(target, searchIndex + 1);
}
else
{
frequency = countFrequency(target, searchIndex + 1);
}
}
return frequency;
}
template<class ItemType>
bool ArrayBag<ItemType>::contains(const ItemType& anEntry) const
{
bool found = false;
int curIndex = 0;
while (!found && (curIndex < itemCount))
{
if (anEntry == items[curIndex])
found = true;
else
curIndex++;
}
return found;
}
Bag.cpp:
#include <iostream>
#include <string>
#include "ArrayBag.h"
using std::cout;
using std::endl;
void displayBag(ArrayBag<std::string>& bag)
{
cout << "The bag contains " << bag.getCurrentSize() << " items:" << endl;
vector<std::string> bagItems = bag.toVector();
int numberOfEntries = (int)bagItems.size();
for (int i = 0; i < numberOfEntries; i++)
{
cout << bagItems[i] << " ";
}
cout << endl << endl;
}
void bagTester(ArrayBag<std::string>& bag)
{
cout << "isEmpty: returns " << bag.isEmpty() << "; should be 1 (true)" << endl;
displayBag(bag);
std::string items[] = { "one","two", "three", "four", "five", "one" };
cout << "Add 6 items to the bag: " << endl;
for (int i = 0; i < 6; i++)
{
bag.add(items[i]);
}
displayBag(bag);
cout << "isEmpty: returns " << bag.isEmpty() << "; should be 0 (false)" << endl;
cout << "getCurrentSize: returns " << bag.getCurrentSize() << "; should be 6" << endl;
cout << "Try to add another entry: add(\"extra\") returns " << bag.add("extra") << endl;
}
int main()
{
ArrayBag<std::string> bag;
cout << "Testing the Array-Based Bag:" << endl;
cout << "The initial bag is empty." << endl;
bagTester(bag);
cout << "All done!" << endl;
std::cin.get();
return 0;
}
Can you please show the makefile, environment, compiler ? I've compiled it whitout problems, I'm using qt creator IDE under windows(mingw32), and the makefile is created automaticly by qmake, so, I supouse that your problem may be in the makefile, I know that it is a comment, but due to my reputation I am not able to make comments, so, after you show the makefile I will can help you.
please avoid mark as negative this answer, I am tryining of help, and increase my reputation. if it answer is not contructive please, let me know and I will remove it.
the output of for code is :
output
I've reproduced your problem and understand what's going on. The unusual construct with include ArrayBag.cpp works fine, as long as you don't compile it, and just use it "as a header". But it's content must appear only once in each translation unit. That's why we have include guards: Any file you #include should have include guards, and ArrayBag.cpp dosn't. Here's how it goes:
You compile Arraybag.cpp, which
includes the declarations in ArrayBag.h Fine, but
ArrayBag.h then includes Arraybag.cpp, which does not have its own include guard
The definitions are parsed, and after the end of Arraybag.cpp, parsing continues back at the end of ArrayBag.h .
We are now done with the first line of the compilation of ArrayBag.cpp, but we are still parsing it: and we go through the rest of ArrayBag.cpp again.
You can still compile ArrayBag.cpp, for the sake of it:
ArrayBag.cpp
// would just be
#include "ArrayBagDefinitions.h"
And ArrayBagDefinitions.h would be your old ArrayBag.cpp file, but with include guards. Your code then compiles fine with vs2017.
In your book, did they mention not to compile ArrayBag.cpp?
In C++, the compiler generates code when a template class is instantiated. Our trusty friend can't do this without a definition. For this reason, the definition needs to be available at compile time (there's more reasons why). For readability, you'll often see people separate the declaration of a template class from the definition.
As the book has shown you, we can take advantage of #include to supply the definition to the compiler while still separating the two.
The caveat here is that you cannot compile the files you used to separate the definition. Depending on whether ArrayBag.cpp is compiled before ArrayBag.h is included somewhere else, the compiler will have a hizzy fit when he finds out that you already tried to define ArrayBag.
Alternatively, you can add an include guard in ArrayBag.cpp, which will prevent the compiler from attempting define ArrayBag again during compilation of ArrayBag.cpp, but I don't advise this. It will add unnecessary time during compilation. After all, we're abusing the simplicity of #include here to mitigate a pain point in the requirements of the compiler.
If you're using Visual Studio, you can treat a .cpp file as a header file by right clicking on the file in the solution explorer > Properties > General > Excluded From Build: Yes
I'm using Visual Studios and when I declare a type, its say:
"Error: Object of abstract class type "set< std::string >" is not allow:
Pure virtual function "setinterface::GetCurrentSize [with type=std::string]" has no overrider"
#include <iostream> // For cout and cin
#include <string> // For string objects
#include "set.h" // For ADT bag
#include "setinterface.h" // For ADT setinterface
#include <vector> // for vector objects
using namespace std;
int main()
{
string clubs[] = { "Joker", "Ace", "Two", "Three",
"Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack",
"Queen", "King" };
// Create our bag to hold cards.
set<string> grabBag;
By the time I get to get to set < string > grabBag is when i get this error. Here is the rest of my code
set.h
#ifndef TEACH_CSCI235_BAGADT_BAG_H_
#define TEACH_CSCI235_BAGADT_BAG_H_
#include "setinterface.h"
template<class ItemType>
class set : public setinterface<ItemType>
{
public:
set(const ItemType& an_item);
int GetCurrentSize() const;
bool IsEmpty() const;
bool Add(const ItemType& new_entry);
bool Remove(const ItemType& an_entry);
void Clear();
bool Contains(const ItemType& an_entry) const;
vector<ItemType> ToVector() const;
private:
int GetIndexOf(const ItemType& target) const;
static const int kDefaultBagSize_ = 6;
ItemType items_[kDefaultBagSize_]; // array of bag items
int item_count_; // current count of bag items
int max_items_; // max capacity of the bag
// Returns either the index of the element in the array items that
// contains the given target or -1, if the array does not contain
// the target.
}; // end Bag
#endif // TEACH_CSCI235_BAGADT_BAG_H_
template<class ItemType>
set<ItemType>::set() : item_count_(0), max_items_(kDefaultBagSize_)
{
return items_[item_count_];
} // end default constructor
template<class ItemType>
int set<ItemType>::GetCurrentSize() const
{
return item_count_;
} // end getCurrentSize
template<class ItemType>
bool set<ItemType>::IsEmpty() const
{
return item_count_ == 0;
} // end isEmpty
template<class ItemType>
bool set<ItemType>::Add(const ItemType& new_entry)
{
bool has_room_to_add = item_count_ < max_items_;
//compares the new entry to every item in item_ and if there is a duplicate, the loop breaks and nothing is added.
if (has_room_to_add)
{
for ( int i =0; i < max_items_; i++)
{
if (items_[i] == new_entry)
break; //ends loop
else if (i==5)
{
items_[item_count_] = new_entry;
item_count_++;
break; //ends loop
} // end if
} // end for
} //end if
return has_room_to_add;
} // end add
template<class ItemType>
bool set<ItemType>::Remove(const ItemType& an_entry)
{
int located_index = GetIndexOf(an_entry);
bool can_remove_item = !IsEmpty() && (located_index > -1);
if (can_remove_item)
{
item_count_--;
items_[located_index] = items_[item_count_];
} // end if
return can_remove_item;
} // end remove
template<class ItemType>
void set<ItemType>::Clear()
{
item_count_ = 0;
} // end clear
template<class ItemType>
bool set<ItemType>::Contains(const ItemType& an_entry) const
{
return GetIndexOf(an_entry) > -1;
} // end contains
template<class ItemType>
vector<ItemType> set<ItemType>::ToVector() const
{
vector<ItemType> bag_contents;
for (int i = 0; i < item_count_; i++)
bag_contents.push_back(items_[i]);
return bag_contents;
} // end toVector
template<class ItemType>
int set<ItemType>::GetIndexOf(const ItemType& target) const
{
bool found = false;
int result = -1;
int search_index = 0;
// if the bag is empty, item_count is zero, so loop is skipped
while (!found && (search_index < item_count_))
{
if (items_[search_index] == target)
{
found = true;
result = search_index;
}
else
{
search_index++;
} // end if
} // end while
return result;
} // end getIndexOf
here is all of setinterface.h
#ifndef TEACH_CSCI235_BAGADT_BAGINTERFACE_H_
#define TEACH_CSCI235_BAGADT_BAGINTERFACE_H_
#include <vector>
#include <cstddef>
using namespace std;
template<class ItemType>
class setinterface
{
public:
/** Gets the current number of entries in this bag.
#return The integer number of entries currently in the bag. */
virtual int GetCurrentSize() const = 0;
/** Sees whether this bag is empty.
#return True if the bag is empty, or false if not. */
virtual bool IsEmpty() const = 0;
/** Adds a new entry to this bag.
#post If successful, newEntry is stored in the bag and
the count of items in the bag has increased by 1.
#param new_entry The object to be added as a new entry.
#return True if addition was successful, or false if not. */
virtual bool Add(const ItemType& new_entry) = 0;
/** Removes one occurrence of a given entry from this bag,
if possible.
#post If successful, anEntry has been removed from the bag
and the count of items in the bag has decreased by 1.
#param an_entry The entry to be removed.
#return True if removal was successful, or false if not. */
virtual bool Remove(const ItemType& an_entry) = 0;
/** Removes all entries from this bag.
#post Bag contains no items, and the count of items is 0. */
virtual void Clear() = 0;
/** Tests whether this bag contains a given entry.
#param an_entry The entry to locate.
#return True if bag contains anEntry, or false otherwise. */
virtual bool Contains(const ItemType& an_entry) const = 0;
/** Empties and then fills a given vector with all entries that
are in this bag.
#return A vector containing all the entries in the bag. */
virtual vector<ItemType> ToVector() const = 0;
}; // end BagInterface
#endif // TEACH_CSCI235_BAGADT_BAGINTERFACE_H_
I started getting this error right after i tried to create a constructor in the set class and when I went to save it, it gave me a notice that it was gonna use something else in order to save my data, I didn't pay much attention to it but I think that may have something to do with this error.
I'm also suppose to "add a constructor that constructs a Set for a single item:" according to my assignment so my constructor might be a good place to look. I'm not even sure if I did it correctly.
I appreciate any help. Thankyou!
I'm trying to solve a queue problem that is required in my assignment.
The details are as follows :
- I am asked to create an automate robust queuing sub-system (note that the each dental clinic has 2 doctors and 4 dentist chairs, 1 x-ray machine on its premise)
- Time-optimised algorithm (different type of treatment). For example, tooth decay would require 30 minutes, checkup would be only 15 minutes, etc.
- Every clinic expected about ~20 and ~15 patients in the morning and afternoon per day respectively.
- The clinic timing is 8am – 12pm, 2pm – 6pm
Upon asking my lecturer, he said that I would need 2 queues(for each doctor), x-ray machines would be an instant process and requires no time at all and in the end of the day, when comparing these 2 queues, the difference of the total duration would be almost equal.
I have been trying to solve this problem but to no avail. Can someone explain how these would be solved?
EDIT :
I have created the queue implementation and a Visit class that is supposed to be enqueued into the queue. What I need to figure out is the algorithm on how to schedule all these visits such that the queues will be time-efficient.
Visit.h
#ifndef Visit_H
#define Visit_H
#include "MC.h"
#include "Doctor.h"
#include "Assistant.h"
#include "Condition.h"
#include "Medicine.h"
#include "Treatment.h"
class Visit
{
private:
std::string date;
std::string time;
double duration;
Staff staff;
MC mc;
bool xRayStatus;
List<Treatment> treatmentList;
List<Condition> conditionList;
List<Medicine> medicineList;
public:
Visit();
Visit(std::string, std::string, double);
std::string getDate();
void addStaff(Staff);
Staff getStaff();
void setMC(MC);
MC getMC();
void addXRay();
bool getXRayStatus();
void addCondition(Condition c);
void addMedicine(Medicine m);
void addTreatment(Treatment t);
List<Treatment> getTreatmentList();
List<Medicine> getMedicineList();
List<Condition> getConditionList();
};
#endif
Visit.cpp
#ifndef Visit_CPP
#define Visit_CPP
#include "Visit.h"
Visit::Visit()
{
}
Visit::Visit(std::string d, std::string t, double dur)
{
date = d;
time = t;
duration = dur;
}
std::string Visit::getDate()
{
return date;
}
void Visit::addStaff(Staff s)
{
staff = s;
}
Staff Visit::getStaff()
{
return staff;
}
void Visit::setMC(MC m)
{
mc = m;
}
MC Visit::getMC()
{
return mc;
}
void Visit::addXRay()
{
xRayStatus = true;
}
bool Visit::getXRayStatus()
{
return xRayStatus;
};
void Visit::addCondition(Condition c)
{
conditionList.add(c);
}
void Visit::addMedicine(Medicine m)
{
medicineList.add(m);
}
void Visit::addTreatment(Treatment t)
{
treatmentList.add(t);
}
List<Treatment> Visit::getTreatmentList()
{
return treatmentList;
}
List<Medicine> Visit::getMedicineList()
{
return medicineList;
}
List<Condition> Visit::getConditionList()
{
return conditionList;
};
#endif
Queue.h
//Queue.h - - Specification of Queue ADT (implemented using Pointers)
#include<string>
#include<iostream>
#include "Visit.h"
using namespace std;
typedef Visit ItemType;
class Queue
{
private:
struct Node
{
ItemType item; // item
Node *next; // pointer pointing to next item
};
Node *frontNode; // point to the first item
Node *backNode; // point to the first item
public:
// constructor
Queue();
//destructor
~Queue();
// check if the queue is empty
bool isEmpty();
// enqueue item at the back of queue
bool enqueue(ItemType& newItem);
// dequeue item from front of queue
bool dequeue();
// dequeue and retrieve item from front of queue
bool dequeue(ItemType& item);
// retrieve item from front of queue
void getFront(ItemType& item);
};
Queue.cpp
/** #file Queue.cpp */
#include <cstddef> // for NULL
#include <iostream>
#include <new> // for bad_alloc
#include "Queue.h" // header file
using namespace std;
Queue::Queue()
{
backNode = NULL;
frontNode = NULL;
} // end default constructor
Queue::~Queue()
{
while (!isEmpty())
dequeue();
} // end destructor
bool Queue::isEmpty()
{
return backNode == NULL;
} // end isEmpty
bool Queue::enqueue(ItemType& item)
{
// create a new node
Node *newNode = new Node;
newNode->item = item;
newNode->next = NULL;
// insert the new node
if (isEmpty())
// insertion into empty queue
frontNode = newNode;
else
// insertion into nonempty queue
backNode->next = newNode;
backNode = newNode; // new node is at back
return true;
} // end enqueue
bool Queue::dequeue()
{
if(!isEmpty())
{ // queue is not empty; remove front
Node *temp = frontNode;
if (frontNode == backNode) // special case?
{ // yes, one node in queue
frontNode = NULL;
backNode = NULL;
}
else
frontNode = frontNode->next;
temp->next = NULL;
delete temp;
temp = NULL;
return true;
} // end if
else
{
cout << "empty queue, cannot dequeue" << endl;
return false;
}
} // end dequeue
bool Queue::dequeue(ItemType& item)
{
if (!isEmpty())
{ // queue is not empty; retrieve front
item = frontNode->item;
dequeue(); // delete front
return true;
} // end if
else
{
cout << "empty queue, cannot dequeue" << endl;
return false;
}
} // end dequeue
void Queue::getFront(ItemType& item)
{
if (!isEmpty())
// queue is not empty; retrieve front
item = frontNode->item;
else
cout << "empty queue, cannot getFront" << endl;
} // end getFront
// End of implementation file.
You need to think of the assignment as an event driven system.
One queue would contain events that need to be handled.
If we have an event class like so:
struct Event
{
virtual bool execute_if_time(const Time& t) = 0;
};
We could have a vector of pointers to events:
typedef std::vector< boost::smart_ptr<Event> > Event_Container;
Event_Container events;
There would be a scheduler loop:
while (1)
{
Time t = now();
for (Event_Container::iterator iter = events.begin();
iter != events.end();
++it)
{
(*iter)->exeute_if_time(t);
}
sleep(/* some duration */)
}
The scheduler would execute events in the container at periodic intervals.
Note: this is only one scheme, as there are many others that would suffice.
The rest of the code is left as an exercise for the reader.
I have a code to remove the first element of a string array.But its deleting the last entered element.How do I delete the first element in the queue without using STL and how do I reset the queue to empty.Here is my class declaration as Queue.h file and QueueImpl.h as its a template file.You got to include all the functions implemented in Queueimpl.h file and then include it in main.I have successfully deleted the element from the queue and I can see that when printing queue but while searching it, the deleted element still exists why is it that
Queue.h
template <class Type>
class Queue
{
private:
int counter;
int Queue_size;
Type* Contents;
int Front, Back;
int items_in_queue = 0;
public:
Queue(int queue_size = 10);
~Queue();
bool Empty() const;
bool Full() const;
void Remove();
int Add(const Type& new_element);
int QueueSize();
Type front();
int search(string &element,int numElm);
void clear();
bool IsDigitsOnly(string &strn);
};
#endif
QueueImpl.h
#pragma once
#ifndef QUEUETEMPLATE_H
#define QUEUETEMPLATE_H
#include<string>
#include "queue.h"
const int MAX_SIZE = 10;
// Constructor
int counter = 0;
template<class Type>
Queue<Type>::Queue(int queue_size) :
Queue_size(queue_size),
Contents(new Type[queue_size + 1]),
Front(0), Back(0)
{}
// Destructor
template<class Type>
Queue<Type> :: ~Queue()
{
delete[] Contents;
}
// Tests
template<class Type>
void Queue<Type>::clear()
{
while (!Empty()) {
Front = Back = -1;
}
}
template<class Type>
bool Queue<Type>::Empty() const
{
return (Front == Back) ? true : false;
}
template<class Type>
bool Queue<Type>::Full() const
{
return ((1 + Back) % (Queue_size + 1) == Front) ? true : false;
}
/
}
#endif
Ok, now it is enough. I do not want to criticize your code style. It would be better if you would demonstrate an example of usage. Without it I assume Type is std::string. I remove <Type> for simplifications. Let start.
IsDigitsOnly does not relate to your class. It is better to move it into a separate function.
Why you need queue_size + 1 of elements in the array Contents if queue_size is desired?
The constructor Queue::Queue initializes an empty queue object, zeros Front and Back. It should be done in Queue::clear: Front = Back = 0 instead of Front = Back = -1.
Simply return Front == Back instead of return (Front == Back) ? true : false.
Queue::Full would be identical to Queue::Empty. They both should check counter.
Queue::Remove: the condition if (Front == Back) is always false, since the same condition is in if (Empty()). The final else is right, since you are using correct Queue_size. You must counter-- there.
In Queue::Add the erroneous Queue_size + 1 is used.
Queue::search does not use Front and Back therefore it is wrong. See below.
Let stop here. I hope you are able to move forward yourself.
New to the 5 and 8.
template<class Type>
bool Queue<Type>::Empty() const
{
return counter == 0;
}
template<class Type>
bool Queue<Type>::Full() const
{
return counter == Queue_size;
}
template<class Type>
int Queue<Type>::search(const Type& element, int numElm)
{
if (numElm < Front || numElm >= Back)
return -1;
// Used as a subscript to search array
for (int index = numElm; index != Back; index = (index + 1) % Queue_size)
{
if (Contents[index] == element) // If the value is found
return index;
}
return -1;
}