Cannot compute collision and compare times in Hash search - c++

there. I am trying to get collision and compare times in Hash search. Yet it doesn't work out. Can anyone point out what the problem is? Thanks very much. Here is my code.
HashSerch.cpp
#include <cstring>
#include <iostream>
#include <iomanip>
using namespace std;
const int TOTAL=32; //32 keywords
const int MAXLEN=10; //length of keyword
const int HASHLEN=41; //length of HASH table
const char* KeyWords[TOTAL] =
{
"auto","double","int","struct","break","else","long","switch",
"case","enum","register","typedef","char","extern","return","union",
"const","float","short","unsigned","continue","for","signed","void",
"default","goto","sizeof","volatile","do","if","while","static",
};
class HASH
{
public:
char keyword[MAXLEN];
int count; //occurrence number
int con; //collision times
};
HASH HS[HASHLEN];
//declaration
int isLetter(char ch);
int isKeyWords(char *word);
int FindHX(char *keyword); //search Hash table
int CreatHX(char *keyword); //create Hash table
int GetFreePos(int key); //get free position when having collision
void ResetHX();
int GetKey(char *keyword); //get Hash value of keywords
int ShowHashTable(int key); //show search results
int isLetter(char ch)
{
if( (ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z') ) return 1;
else return 0;
}
int FindHX(char *keyword, int &cmp_count) //search Hash table
{
int key,find,tem=0;
if(!isKeyWords(keyword)) return -1;
key=GetKey(keyword);
if(strcmp(HS[key].keyword,keyword)==0)
{
cmp_count++;
return key;
}
for(find=key+1;find<HASHLEN;find++) //if keyword exsits
{
cmp_count++; //count compare times
tem++; //count collision times
if(strcmp(HS[find].keyword,keyword)==0)
{
HS[find].con=tem;
return find;
}
}
for(find=0;find<key;find++)
{
cmp_count++;
tem++;
if(strcmp(HS[find].keyword,keyword)==0)
{
HS[find].con=tem;
return find;
}
}
return -1;
}
int CreatHX(char *keyword) //create Hash table
{
int key;
if(!isKeyWords(keyword)) return -1;
key=GetKey(keyword); //get Hash value of keywords
if(strlen(HS[key].keyword)>0) //if the keyword exists
{
if(strcmp(HS[key].keyword,keyword)==0) //if equals to position in Hash table
{
HS[key].count++;
return 1;
}
key=FindHX(keyword, cmp_count); //not equal
if(key<0)
{
key=GetFreePos(GetKey(keyword));
if(key<0) return -1;
strcpy(HS[key].keyword,keyword); //insert keyword into Hash table
}
if(key<0) return -1;
HS[key].count++;
}
else //if position is empty, insert keyword
{
strcpy(HS[key].keyword,keyword);
HS[key].count++;
}
return 1;
}
int GetFreePos(int key) //get free position
{
int find,tem=0;
if(key<0||key>=HASHLEN) return -1;
for(find=key+1;find<HASHLEN;find++) //positions afterwards
{
tem++;
if(strlen(HS[find].keyword)==0)
{
HS[find].con=tem;
return find;
}
}
for(find=0;find<key;find++) //position forewards
{
tem++;
if(strlen(HS[find].keyword)==0)
{
HS[find].con=tem;
return find;
}
}
return -1; //Hash table is full
}
void ResetHX()
{
int i;
for(i=0;i<HASHLEN;i++)
{
strcpy(HS[i].keyword,"");
HS[i].count=0;
HS[i].con=0;
}
}
int GetKey(char *keyword) //get Hash value of keywords
{
//Hash(Key)=[(initial letter)*100+(tail letter)] Mod 41
return ( keyword[0]*100+keyword[strlen(keyword)-1] ) % 41;
}
int isKeyWords(char *word)
{
int i;
for(i=0;i<TOTAL;i++)
if(strcmp(word,KeyWords[i])==0) return 1;
return 0;
}
int ShowHashTable(int key) //show results
{
int hash_count = 0;
if(key < 0 || key >= HASHLEN)
{
cout << "Error! Invalid key word!" << endl;
return 0;
}
if(strlen(HS[key].keyword) == 0)
{
cout << "[" << key << "]" << setw(12) << "N/A" << endl;
return 0;
}
cout << "[" << key << "]" << setw(12) << HS[key].keyword << setw(12) << "Count: " << HS[key].count << endl;
hash_count++;
return hash_count;
}
main.cpp
#include <iostream>
#include <cstring>
#include "HashSearch.h"
extern HASH HS[MAXLEN];
using namespace std;
int hash_count = 0;
for(int i = 0; i < HASHLEN; i++)
{
hash_count = hash_count + ShowHashTable(i);
}
cout << "Amount of key words: " << hash_count << endl << endl;
int conf_count = 0;
cout << setiosflags(ios::left) << setw(15) << "[Index]" << setiosflags(ios::left) << setw(20)
<< "[KeyWords]" << setiosflags(ios::left) << setw(20) << "[Conflicts]" << endl;
for(int i = 0; i < HASHLEN; i++)
{
if(strlen(HS[i].keyword) > 0)
{
int key = Hash(HS[i].keyword);
if(key != i)
{
conf_count++;
//cout << HS[i].con << endl;
cout << setiosflags(ios::left) << setw(15) << i << setiosflags(ios::left) << setw(25)
<< HS[i].keyword << setiosflags(ios::left) << setw(20) << HS[i].con << endl;
}
}
}
if(conf_count == 0)
cout << "No conflicts!" << endl;
else
cout << "Amount of conflict keywords: " << conf_count << endl << endl;
I first imported a source txt file and created a Hash table. It seems that all goes well. But when I want to get the compare times and collision times, the variable HS.con(to count collision times) and cmp_count(to count compare times) don't accumulate correctly. The value stays 0 if watching in debug mode. And how can I get correct count?

Related

C++ Array values being altered at element 4 after throwing exception

The requirements for the program state that the try/catch must be placed in the main.cpp as below:
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
When it accesses the method:
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
It doesn't seem to matter which variation of throwing I use, my array gets destroyed afterward. It works fine if it stays within bounds, or I work it to not throw from the method (doing the error checking elsewhere), but the requirements state that it has to be that way, so I must be missing something. Full code below:
main.h:
#ifndef MAIN_H
#define MAIN_H
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER
***********************************/
#include <iostream> /* cout, endl */
#include "mylist.h"
#include <stdexcept>
#define LISTSIZE 10
using std::cout;
using std::endl;
int elementResult;
#endif /* MAIN_H */
main.cpp:
#include "main.h"
int main(int argc, char** argv) {
/***********************************
* DO NOT MODIFY THIS FILE OTHER THAN
* TO ADD YOUR COMMENT HEADER AND
* UNCOMMENT THINGS AS YOU COMPLETE
* THE FUNCTIONALITY OF YOUR LIST OBJECT
***********************************/
/* This will create a "list" of size LISTSIZE
* and initialize it to all zeros */
cout << "create and initialize mylist" << endl;
MyList mylist(LISTSIZE);
mylist.printArray();
cout << endl;
/* This will set the list to all 50 */
cout << "set mylist to all 50" << endl;
mylist.setArray(50);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers -2 to 4" << endl;
mylist.setRandom(-2,4);
mylist.printArray();
cout << endl;
/* This will fail and set the array to the
* default random 1-10 values */
cout << "attempt to set to random numbers 4 to 4" << endl;
mylist.setRandom(4,4);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 1-100 values */
cout << "attempt to set to random numbers 1 to 100" << endl;
mylist.setRandom(1,100);
mylist.printArray();
cout << endl;
/* This will succeed and set the array to the
* random 500-1000 values */
cout << "attempt to set to random numbers 500 to 1000" << endl;
mylist.setRandom(1000,500);
mylist.printArray();
cout << endl;
/* These next two sets will succeed and set the 1st and last
* elements to 1000 and 2000 respectively */
if(mylist.setElement(1000, 0)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(2000, LISTSIZE-1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
/* These next two sets will fail and leave the array unmodified */
if(mylist.setElement(9999, -1)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
if(mylist.setElement(9999, LISTSIZE)){
cout << "Element Set" << endl;
} else {
cout << "Element NOT Set" << endl;
}
mylist.printArray();
cout << endl;
cout << "Testing new and/or modified code..." << endl << endl;
cout << "printing the array element by element using: int getElement(int);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
try{
elementResult = mylist.getElement(i);
cout << elementResult << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
mylist.printArray();
cout << "attempting to get element 4000 using: int getElement(int);" << endl;
try{
cout << mylist.getElement(4000) << endl;
} catch(int e){
cout << "Error: Index out of range." << endl;
}
cout << endl;
cout << "printing the array element by element using: int getElement(int,int*);" << endl;
cout << "(going one too far to test out of range)" << endl;
for(int i=0; i<=LISTSIZE; i++){
if(mylist.getElement(i, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
}
cout << endl;
cout << "attempting to get element 4000 using: int getElement(int,int*);" << endl;
if(mylist.getElement(4000, &elementResult)){
cout << elementResult << endl;
} else {
cout << "Error: Index out of range." << endl;
}
return 0;
}
mylist.h:
#ifndef MYLIST_H
#define MYLIST_H
#include <iostream> /* cout, endl */
#include <stdlib.h> /* srand, rand, atoi */
#include <time.h> /* time */
#include <stdexcept>
// you can add libraries if you need them, but you shouldn't
// DO NOT MODIFY THESE DEFINES
#define RMIN 1
#define RMAX 10
#define DEFAULT_SIZE 10
using std::cout;
using std::endl;
class MyList {
public:
// DO NOT MODIFY THESES NEXT TWO
MyList(int); // constructor
~MyList(); // destructor
int getElement(int);
void setArray(int);
bool setElement(int, int);
void setRandom(int, int);
void printArray();
bool getElement(int, int*);
private:
// these are the only attributes allowed
// DO NOT ADD OR MODIFY THEM
int length;
int *array;
};
#endif //MYLIST_H
mylist.cpp:
#include "mylist.h"
// constructor
MyList::MyList(int size) {
srand(time(NULL)); // call only once!
if(size < 1){
size = DEFAULT_SIZE;
}
MyList::length = size;
MyList::array = new int(size);
setArray(0);
}
// destructor
MyList::~MyList() {
//delete[] MyList::array;
}
void MyList::printArray() {
cout << "[";
for (int i = 0; i < length; i++){
if (i == length - 1){
cout << array[i];
}else{
cout << array[i] << " ";
}
}
cout << "]" << endl;
}
void MyList::setArray(int setArrayTo){
for (int i = 0; i < length; i++){
MyList::array[i] = setArrayTo;
}
}
void MyList::setRandom(int numOne, int numTwo){
bool isValidRandom = true;
int randMin, randMax;
if((numOne < RMIN) || (numTwo < RMIN) || (numOne == numTwo)){ isValidRandom = false; }
if(isValidRandom == true){
if(numTwo < numOne){
randMin = numTwo;
randMax = numOne;
} else {
randMin = numOne;
randMax = numTwo;
}
} else {
randMin = RMIN;
randMax = RMAX;
}
for(int i = 0;i < length; i++){
MyList::array[i] = rand() % randMax + randMin;
}
}
bool MyList::setElement(int passedValue, int arrayIndex){
bool isInRange = true;
if ((arrayIndex < 0)||(arrayIndex > length - 1)){
isInRange = false;
}
if (isInRange == true){
MyList::array[arrayIndex] = passedValue;
}
return isInRange;
}
int MyList::getElement(int passedIndex){
if((passedIndex < 0) || (passedIndex > length -1)){
throw 0;
}
return array[passedIndex];
}
bool MyList::getElement(int passedIndex, int *iPtr){
bool isItValid = true;
if((passedIndex >= 0) && (passedIndex < length)){
*iPtr = MyList::array[passedIndex];
} else {
isItValid = false;
}
return isItValid;
}
Output

C++ Depth First Search of Trie with prefix parameter

I'm trying to implement a trie that can print out the frequency of words with a given prefix.
Edit: Thanks to #kaidul-islam finding my error with the following error:
new_word->child[letter]->prefixes_++;
Below is the fixed code:
Trie Class:
class Trie
{
public:
Trie(): prefixes_(0), is_leaf_(false), frequency_(0)
{
for (int i=0; i<26; i++)
{
child[i] = nullptr;
}
}
virtual ~Trie();
//Child nodes of characters from a-z
Trie *child[26];
//vector<Trie> child;
int prefixes_;
//accessor & mutator functions
bool GetIsLeaf() { return is_leaf_; }
void SetIsLeaf(bool val) { is_leaf_ = val; }
int GetFrequency() { return frequency_; }
void SetFrequency(int val) { frequency_ = val; }
int GetPrefixes() { return prefixes_; }
void SetPrefixes(int val) { prefixes_ = val; }
bool is_leaf_;
private:
//bool is_leaf_;
int frequency_;
};
Function in Question:
void AddWord(string &word, Trie *root)
{
Trie *new_word = root;
new_word->prefixes_++;
for(unsigned int i = 0 ; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a'; //extract character of word
if(new_word->child[letter] == nullptr)
{
new_word->child[letter] = new Trie;
}
/*cout << "not value of x: " << new_word->child[letter]->GetPrefixes() << endl;
int x = (new_word->child[letter]->GetPrefixes())+1;
cout << "value of x: " << x << endl;
new_word->child[letter]->SetPrefixes(x);*/
new_word->child[letter]->prefixes_++;
new_word = new_word->child[letter];
}
new_word->SetFrequency(new_word->GetFrequency()+1);
/*
cout << "Word: " << word << endl;
cout << "frequency: " << new_word->GetFrequency() << endl;
cout << "prefixes: " << new_word->GetPrefixes() << endl;
cout << "is leaf: " << new_word->GetIsLeaf() << endl << endl;
*/
}
After a quick inspection, I found you didn't initialize member variables in your constructor.
Trie(): prefixes_(0),
is_leaf_(false),
frequency_(0) {
for(int i = 0; i < 26; i++) {
child[i] = nullptr;
}
}
Unlike global variable, there is no guarantee that prefixes_ will be 0 by default on declaration. And child[i] is not guaranteed to be nullptr too. You need to initialize everything.

Negative value not being added to Array

Problem
I have 2 arrays, one for positive numbers, one for negative numbers. For some reason, if the first number to be added is a negative number, it creates the array space to add the number yet the number inserted will always be 0.
Code for adding
Here is my add method, it determines if the value is negative or positive and adds the value to the appropriate array:
bool MyClass::addInt(int valueToBeInserted){
if (valueToBeInserted >= 0){
if (posArrayIterator >= sizeOfMyArray){
return false;
} else {
cout << "added " << valueToBeInserted << "\n" << endl;
myPArray[posArrayIterator] = valueToBeInserted;
posArrayIterator ++;
return true;
}
} else {
if (negArrayIterator >= sizeOfMyArray){
return false;
} else {
cout << "added " << valueToBeInserted << "\n" << endl;
myNarray[negArrayIterator] = valueToBeInserted;
negArrayIterator ++;
return true;
}
}
}
Output
With the following test:
b.addInt(-1);
b.addInt(-3);
b.addInt(-9);
The expected output would be
[-1, -3, -9]
but output is
[-3, -9, 0].
Any help is much appreciated.
Since you are not posting the whole class I can only guess where the problem is.
1) Are posArrayIterator and negArrayIterator initialized to 0? They should be!
2) What is a value of sizeOfMyArray?
There is nothing wrong with your bool MyClass::addInt(int valueToBeInserted)
See example below:
class MyClass
{
private:
int sizeOfMyArray;
int posArrayIterator;
int negArrayIterator;
int myNarray[20];
int myPArray[20];
public:
MyClass(){
sizeOfMyArray = 20;
posArrayIterator = 0;
negArrayIterator = 0;
};
bool addInt(int value);
void printNArray()
{
cout << "[ ";
for (int i=0; i<negArrayIterator; i++)
{
cout << myNarray[i];
if ( (i+1) < negArrayIterator )
{
cout << ", ";
}
}
cout << "]";
}
};
bool MyClass::addInt(int valueToBeInserted){
if (valueToBeInserted >= 0){
if (posArrayIterator >= sizeOfMyArray){
return false;
} else {
cout << "added " << valueToBeInserted << "\n" << endl;
myPArray[posArrayIterator] = valueToBeInserted;
posArrayIterator ++;
return true;
}
} else {
if (negArrayIterator >= sizeOfMyArray){
return false;
}
else {
cout << "added " << valueToBeInserted << "\n" << endl;
myNarray[negArrayIterator] = valueToBeInserted;
negArrayIterator ++;
return true;
}
}
}
int main()
{
MyClass b;
b.addInt(-1);
b.addInt(-3);
b.addInt(-9);
b.printNArray();
return 0;
}
Output:
added -1
added -3
added -9
[ -1, -3, -9]

C++ class and function output issue

I'm having problems with my program's output. It keeps spitting out 12345.
Here's the details:
It's split in three files: program8.cpp (the part that runs tests), myRandom.cpp (implementation of the class), and myRandom.h (specification of the class).
myRandom.h:
#ifndef MYRANDOM_H_
#define MYRANDOM_H_
class myRandom
{
public:
myRandom(); //Constructor
~myRandom(); //Destructor
void seed(unsigned long theSeed); //Mutator for current
unsigned long next(); //Mutator or Accessor for current
int randInt(int start, int end); //Scales result to a range
double randNormal(); //Future expansion
private:
unsigned long current; //Current random #
static const unsigned long a = 1103515245; //Multiplier for LGC
static const unsigned long c = 12345; //Increment for LGC
static const unsigned long m = 2147483648; //Modulus for LGC
};
#endif /* MYRANDOM_H_ */
myRandom.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
myRandom::myRandom() //Constructor
{
current = 0;
}
myRandom::~myRandom() //Destructor
{
}
void myRandom::seed(unsigned long theSeed) //Mutator for current
{
if (theSeed < 0 || theSeed > m-1)
{
// ERROR
return;
}
else
current = theSeed;
}
unsigned long myRandom::next() //Mutator or Accessor for current
{
if (current < 0)
{
cout << "Error: cannot set seed to a negative number" << endl;
return 0;
}
else
{
current = (m*current+c)%m; //Formula
return current;
}
}
int myRandom::randInt(int start, int end) //Scales result to a range
{
if (start >= end)
{
cout << "Error: cannot set start greater than or equal to end" << endl;
return 0;
}
else
{
return ((this->next() % (end - start)) + start);
}
}
double myRandom::randNormal() //Future expansion
{
cout << "Warning: randNormal not implemented" << endl;
return 0;
}
program8.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
int main()
{
myRandom theRand;
unsigned long theSeed;
cout << "Verify that the sequence generated by next() is the same on each run" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.next() << endl;
}
cout << "Verify that you can set the seed to 0 and 1" << endl;
theSeed = 0;
cout << theRand.next() << endl;
theSeed = 1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to -1 generates an error" << endl;
theSeed = -1;
cout << theRand.next() << endl;
cout << "Verify that you can set the seed to m-2 and m-1" << endl;
theSeed = 2147483648-2;
cout << theRand.next() << endl;
theSeed = 2147483648-1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to m generates and error" << endl;
theSeed = 2147483648;
cout << theRand.next() << endl;
cout << "Verify that next() produces a sequence predicted by hand/calc for the chosen seed" << endl;
cout << "Please enter a seed: ";
cin >> theSeed;
cout << theRand.next() << endl;
cout << "Verify that using start == end generates and error. Set both to 10." << endl;
theRand.randInt(10,10);
cout << theRand.next() << endl;
cout << "Verify that using start > end generates and error. Set start to 10 and end to 5." << endl;
theRand.randInt(10,5);
cout << theRand.next() << endl;
theRand.seed(theSeed);
cout << "Testing randInt for start=0 end=1,000" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.randInt(0 , 1000) << endl;
}
return 0;
}
I think the problem lies in the next() function, since that's what gets called all those times in program8.cpp cout statements. I could understand getting 12345 once, but it should be updated once that function runs successive times. I apologize if it's a dumb question. Thank you for your time and patience.
Your problem isn't a code specific one - it is Math-related from here:
current = (m*current+c)%m;
This always returns the value of c if c < m, otherwise (or more generally) it returns c % m. Why? From this theorem:
(m*n + a)%m = a
Example:
m = 10
n = 3
a = 7
(10*3 + 7)%10 = 7
See this for more:
http://en.wikipedia.org/wiki/Modulo_operation

Errors within Main program using classes

I just have a few errors of the same type in my main program. My college professor is not answering my emails so I have to resort to asking you guys. In my main program I have several errors somewhat similar to this: "request for member which is of non-class type." Program01 is basically testing every function in ListType.h, OListType.h, and UListType.h to make sure everything works correctly. Any help you can provide in a timely fashion will be appreciated.
Here is ListType.h:
#ifndef LISTTYPE_H_INCLUDED
#define LISTTYPE_H_INCLUDED
#include <iostream>
class ListType {
public:
ListType(size_t=10);
ListType(const ListType&);
virtual ~ListType();
virtual bool insert(int)=0;
virtual bool eraseAll();
virtual bool erase(int)=0;
virtual bool find(int) const=0;
size_t size() const;
bool empty() const;
bool full() const;
friend std::ostream& operator << (std::ostream&, const ListType&);
const ListType& operator= (const ListType&);
protected:
int *items;
size_t capacity;
size_t count;
};
#endif // LISTTYPE_H_INCLUDED
Here is ListType.cpp:
#include "ListType.h"
ListType::ListType (size_t a) {
capacity = a;
count = 0;
items = new int [capacity];
}
ListType::ListType(const ListType& newlist) {
capacity = newlist.capacity;
count = newlist.count;
items = new int [capacity];
for (size_t i = 0; i < count; ++i)
items[i] = newlist.items[i];
}
ListType::~ListType() {
delete [] items;
}
bool ListType::eraseAll() {
count = 0;
return 0;
}
size_t ListType::size() const {
return (count);
}
bool ListType::empty() const {
return (count == 0);
}
bool ListType::full() const {
return (count == capacity);
}
std::ostream& operator << (std::ostream& out, const ListType& my_list) {
if (!my_list.empty()) {
for (size_t i = 0; i < my_list.count; ++i){
out << my_list.items[i] << ',';
}
}
return out;
}
const ListType& ListType::operator= (const ListType& rightObject) {
if (this != & rightObject) {
delete [] items;
capacity = rightObject.capacity;
count = rightObject.count;
items = new int[capacity];
for (size_t i = 0; i < count; ++i) {
items[i] = rightObject.items[i];
}
}
return *this;
}
Here is UListType.h:
#ifndef ULISTTYPE_H_INCLUDED
#define ULISTTYPE_H_INCLUDED
#include <iostream>
class UListType: public ListType {
public:
UListType(size_t=10);
bool insert(int);
bool erase(int);
bool find(int) const;
};
#endif // ULISTTYPE_H_INCLUDED
Here is UListType.cpp:
#include "ListType.h"
#include "UListType.h"
UListType::UListType (size_t c): ListType(c) {}
bool UListType::insert(int item) {
if (full()) {
int *newitems;
capacity *=2;
newitems = new int[capacity];
for (size_t i =0; i < count; ++i){
newitems[i] = items[i];
}
delete [] items;
items = newitems;
}
items[count++] = item;
return true;
}
bool UListType::erase(int item) {
bool result = false;
size_t i=0;
while ( i < count && items [i] != item) {
++i;
}
if (i < count) {
items[i] = items[-- count];
result = true;
}
return result;
}
bool UListType::find(int item) const {
size_t i = 0;
while (i < count && items [i] != item) {
++i;
}
return i < count;
}
Here is OListType.h:
#ifndef OLISTTYPE_H_INCLUDED
#define OLISTTYPE_H_INCLUDED
#include <iostream>
class OListType: public ListType {
public:
OListType(size_t=10);
bool insert(int);
bool erase(int);
bool find(int) const;
};
#endif // OLISTTYPE_H_INCLUDED
Here is OListType.cpp:
#include "ListType.h"
#include "OListType.h"
OListType::OListType(size_t c): ListType(c) {}
bool OListType::insert(int item) {
size_t i = count;
if (full()) {
int *newitems;
capacity *=2;
newitems = new int[capacity];
for(size_t j=0; j < count; ++j) {
newitems[j] = items[i];
}
delete [] items;
items = newitems;
}
while (i > 0 && items[i-1] > item){
items[count++] = item;
}
return true;
}
bool OListType::erase(int item) {
bool found=false;
size_t i=0, j= count-1, mid;
while (i <= j && !(found)){
mid = (i + j)/2;
if (item < items [mid])
j = mid - 1;
else if (item > items [mid])
i = mid + 1;
found = items [mid] == item;
}
if (found) {
for (i = mid; i < count - 1; ++i) {
items [i] = items [i +1];
}
--count;
}
return found;
}
bool OListType::find (int item) const {
bool found=false;
size_t i=0, j= count-1, mid;
while (i <= j && !(found)){
mid = (i + j)/2;
if (item < items [mid])
j = mid - 1;
else if (item > items [mid])
i = mid + 1;
found = items [mid] == item;
}
return found;
}
Here is Program01.cpp:
#include "ListType.h"
#include "UListType.h"
#include "OListType.h"
#include <iostream>
using namespace std;
int main() {
OListType list[5] = {165, 16, 118, 212, 104};
UListType ranlist[10] = {243, 300, 154, 153, 592, 124, 195, 217, 289, 405};
UListType UListAssignmentTest;
OListType OListAssignmentTest;
cout << "The Ordered List before operations:" << endl;
cout << list << endl << endl;
if(list.empty()) **<-- HERE BE THE ERROR**
cout << "The list is empty, therefore it is true.";
else
cout << "The list is full or partially full, therefore it is false";
cout << endl << endl;
if(list.full())
cout << "The list is full, therefore it is true.";
else
cout << "The list is partially full or empty, therefore it is false";
cout << endl << endl;
list.insert(25);
cout << endl << endl;
cout << "The Ordered list after Insert:" << endl;
cout << list << endl << endl;
list.find(25);
cout << endl << endl;
list.find(30);
cout << endl << endl;
list.erase(25);
cout << endl << endl;
cout << "The Ordered List after Erase:" << endl;
cout << list << endl << endl;
cout << "The Unordered List before operations:" << endl;
cout << ranlist << endl << endl;
if(ranlist.empty())
cout << "The list is empty, therefore it is true.";
else
cout << "The list is full or partially full, therefore it is false";
cout << endl << endl;
if(ranlist.full())
cout << "The list is full, therefore it is true.";
else
cout << "The list is partially full or empty, therefore it is false";
cout << endl << endl;
ranlist.insert(25);
cout << endl << endl;
cout << "The Unordered List after Insert:" << endl;
cout << ranlist << endl << endl;
ranlist.find(25);
cout << endl << endl;
ranlist.find(30);
cout << endl << endl;
ranlist.erase(25);
cout << endl << endl;
cout << "The Unordered List after Erase:" << endl;
cout << ranlist << endl << endl;
cout << "Testing Ordered List Assignment Operator" << endl;
OListAssignmentTest = list;
cout << OListAssignmentTest << endl << endl;
cout << "Testing Unordered List Assignment Operator" << endl;
UListAssignmentTest = ranlist;
cout << UListAssignmentTest << endl << endl
cout << "Testing Ordered List Copy Constructor" << endl;
OListType OListVariable = list;
cout << OListVariable << endl << endl;
cout << "Testing Unordered List Copy Constructor" << endl;
UListType UListVariable = ranlist;
cout << UListVariable << endl << endl;
cout << "Testing Erase All for OList" << endl;
list.eraseAll();
cout << "OList values now: " << list.empty() << endl << endl;
cout << "Testing Erase All for UList" << endl;
ranlist.eraseAll();
cout << endl << "UList values now: " << ranlist.empty() << endl;
return 0;
}
OListType list[5] = {165, 16, 118, 212, 104};
This line declares an array of 5 OListType types. This doesn't seem correct.
You want to declare one OLIstType and insert 5 values into it. If not, please clarify what that line is supposed to denote.
Here is probably what you are supposed to do:
OListType list;
list.insert(165);
list.insert(16); // etc...