I need help using the "==" in this solution - c++

The function contains(Object obj) returns true even though an object of that value is not in the pointer array. I have tried to overload the "==" function in my class Rec. It is using the function but the results are not what I want.
This is an attempt at a solution to a homework problem.
Design a class template, Collection, that stores a collection of Objects (in an array), along with the current size of the collection. Provide public functions isEmpty, makeEmpty, insert, remove, and contains. contains(x) returns true if and only if an Object that is equal to x is present in the collection.
I have tried other ways but I can't use nullptr as assignment.
#include "pch.h"
#include <iostream>
using namespace std;
template <typename Object>
class Collection {
public:
int ndx = 0;
Object *data[10] = { nullptr };
void insert(Object obj) {
if (ndx == 10) {
cout << "Container is full!!" << endl;
}
else {
data[ndx] = &obj;
//cout << data[ndx]->area() << endl;
++ndx;
cout << "Inserted in Location: " << ndx - 1 << endl;
}
}
void isEmpty() {
if (ndx > 0) {
cout << "Not empty " << ndx << " items!" << endl;
}
else {
cout << "Is empty, " << ndx << " items!" << endl;
}
}
void makeEmpty() {
for (int i = 0; i < ndx; i++)
data[i] = nullptr;
ndx = 0;
cout << "It is Empty!" << endl;
}
void remove(Object obj) {
cout << obj.area() << "here" << endl;
int index = -1;
for (int i = 0; i < ndx; i++) {
if (data[i] == obj) {
index = i;
}
}
if (index != -1) {
if (index == ndx - 1)
--ndx;
else {
for (int i = index; i < ndx; i++) {
data[i] = data[i + 1];
}
--ndx;
data[ndx] = nullptr;
}
cout << "Object Removed Location: " << index << endl;
}
else {
cout << "Object not found!" << endl;
}
}
bool contains(Object obj) {
for (int i = 0; i < ndx; i++) {
if (data[i] == obj) {
return true;
}
}
return false;
}
};
class Rec {
public:
int width;
int hieght;
void setValues(int &w, int &h) {
width = w;
hieght = h;
}
void setWidth(int &w) {
width = w;
}
void setHieght(int &h) {
hieght = h;
}
int area() { return width * hieght; };
bool operator==(const Rec& rhs)const {
cout << "used Normal" << endl;
return (width == rhs.width) && (hieght == rhs.hieght);
}
};
bool operator==(Rec * lhs, Rec rhs) {
cout << "used *" << endl;
return (lhs->width == rhs.width) && (lhs->hieght == rhs.hieght);
}
int main()
{
Collection<Rec> test;
for (int i = 0; i < 11; i++) {
Rec r;
r.setValues(i, i);
test.insert(r);
}
Rec r;
int i = 22;
r.setValues(i, i);
bool t = test.contains(r);
cout << "Here?: " << t << endl;
r.setValues(i, i);
test.remove(r);
test.makeEmpty();
//cout << test.data[6]->area() << endl;
return 0;
}
I want it to return false.

Related

Operator overloading += to add new object

Learning operator overloading in this project, and below in the ship.cpp file is where I think my error is.
This is the test file, I cannot change this:
#include <iostream>
#include "Ship.h"
#include "Ship.h"
#include "Engine.h"
#include "Engine.h"
using namespace std;
using namespace sdds;
void printHeader(const char* title)
{
char oldFill = cout.fill('-');
cout.width(40);
cout << "" << endl;
cout << "|> " << title << endl;
cout.fill('-');
cout.width(40);
cout << "" << endl;
cout.fill(oldFill);
}
int main()
{
{
printHeader("T1: Testing Constants");
cout << "TYPE_MAX_SIZE: " << sdds::TYPE_MAX_SIZE << endl;
cout << "MIN_STD_POWER: " << sdds::MIN_STD_POWER << endl;
cout << "MAX_STD_POWER: " << sdds::MAX_STD_POWER << endl;
cout << endl;
}
{
printHeader("T2: Testing Default Constructor");
Ship invalid;
invalid.display();
invalid += Engine("D2", 2.1);
cout << endl;
}
Engine engines[] = {
Engine("V8", 4.4),
Engine("V8", 5.0),
Engine("Inline", 4.1),
Engine("D3", 7.0),
Engine("D0", 2.0),
Engine("D1", 3.2),
};
{
printHeader("T3: Testing Custom Constructor");
Ship titanic("cruiser", engines, 6);
titanic.display();
cout << endl;
}
{
printHeader("T4: Testing Conversion to Bool Operator");
Ship invalid;
Ship titanic("liner", engines, 1);
if (invalid)
cout << "1. Test Failed! Object should be invalid.\n";
else
cout << "1. Test succeeded!\n";
if (titanic)
cout << "2. Test succeeded!\n";
else
cout << "3. Test Failed! Object should be valid.\n";
cout << endl;
}
{
printHeader("T5: Testing += and < Operators");
Ship titanic("liner", engines, 3);
char type[]{ "D0" };
while (titanic < sdds::MIN_STD_POWER)
{
type[1]++;
cout << "Ship not up to standard. Required power: "
<< sdds::MIN_STD_POWER << endl;
titanic += Engine(type, 2.1);
}
titanic.display();
if (sdds::MAX_STD_POWER < titanic)
cout << "Too much power." << endl;
else
cout << "Ship doesn't exceed power regulation of: "
<< sdds::MAX_STD_POWER << endl;
}
return 0;
}
This is my Ship.cpp file. My error is in the += operator function, where I have to add an engine but don't understand how I should approach it.
#include <iostream>
#include <cstring>
#include "Ship.h"
using namespace std;
namespace sdds {
Ship::Ship(){
m_type[0] = '\0';
m_engCnt = 0;
}
Ship::Ship(const char* type, const Engine engines[], int cnt){
if (type != nullptr && engines != nullptr && cnt > 0) {
// create a valid ship
strncpy(m_type, type, TYPE_MAX_SIZE);
for (int i = 0; i < cnt; i++) {
m_engines[i] = engines[i];
}
m_engCnt = cnt;
}else{
m_type[0] = '\0';
m_engCnt = 0;
}
}
Ship::operator bool() const {
// return true if the ship is valid (not empty)
if(m_type[0] == '\0' || m_engCnt == 0){
return false;
}else{
return true;
}
}
Ship& Ship::operator+=(Engine e){
if (!*this) {
cout << "The Object is not valid! Engine cannot be added!" << endl;
return *this;
}else if (m_engCnt == NUM_OF_ENGINES){
return *this;
}else{
// ERROR I BELIEVE IS HERE --> I dont understand the syntax to add engine here
m_engCnt++;
return *this;
}
}
double Ship::calculatePower() const {
double power = 0;
for (int i = 0; i < m_engCnt; i++) {
power += m_engines[i].get() * 5;
}
return power;
}
void Ship::display()const{
if (*this) {
cout << m_type << " - " << calculatePower() << endl;
Engine e;
for (int i = 0; i < m_engCnt; i++) {
m_engines[i].display();
}
}else{
cout << "No available data" << endl;
}
}
bool Ship::operator<(double power) const{
if (calculatePower() < power) {
return true;
}else{
return false;
}
}
bool operator<(double power, const Ship& theShip){
if (power < theShip.calculatePower()) {
return true;
}else{
return false;
}
}
}
This is my engine.cpp file:
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <string.h>
#include "Engine.h"
using namespace sdds;
using namespace std;
namespace sdds {
Engine::Engine(){
m_type[0] = '\0';
m_size = 0.0;
}
Engine::Engine(const char* type, double size){
strncpy(m_type, type, TYPE_MAX_SIZE);
m_size = size;
}
double Engine::get() const{
return m_size;
}
void Engine::display() const{
cout << m_size << " liters - " << m_type << endl;
}
}
This should be the output, but my function is stuck in the while loop:
|> T5: Testing += and < Operators
----------------------------------------
Ship not up to standard. Required power: 90.111
Ship not up to standard. Required power: 90.111
Ship not up to standard. Required power: 90.111
liner - 99
4.4 liters - V8
5 liters - V8
4.1 liters - Inline
2.1 liters - D1
2.1 liters - D2
2.1 liters - D3
Ship doesn't exceed power regulation of: 99.999
Your operator+= is not doing anything with the Engine that is passed to it. Your Ship class has an m_engines array, which your Ship constructor adds Engines to (without regard to NUM_OF_ENGINES, though), but your operator+= is not.
Your constructor and operator+= should look more like this instead:
Ship::Ship(const char* type, const Engine engines[], int cnt){
if (type != nullptr && engines != nullptr && cnt > 0) {
// create a valid ship
strncpy(m_type, type, TYPE_MAX_SIZE);
if (cnt > NUM_OF_ENGINES) cnt = NUM_OF_ENGINES; // <-- ADD THIS LINE!
for (int i = 0; i < cnt; ++i) {
m_engines[i] = engines[i];
}
m_engCnt = cnt;
}else{
m_type[0] = '\0';
m_engCnt = 0;
}
}
Ship& Ship::operator+=(Engine e){
if (!*this) {
cout << "The Object is not valid! Engine cannot be added!" << endl;
return *this;
}else if (m_engCnt == NUM_OF_ENGINES){
return *this;
}else{
m_engines[m_engCnt] = e; // <-- ADD THIS LINE!!!
m_engCnt++;
return *this;
}
}
I would suggest re-writing the constructor and operator+= to look more like this instead:
Ship::Ship(const char* type, const Engine engines[], int cnt){
strncpy(m_type, type != nullptr ? type : "", TYPE_MAX_SIZE);
if (engines != nullptr && cnt > 0) {
if (cnt > NUM_OF_ENGINES) cnt = NUM_OF_ENGINES;
for (int i = 0; i < cnt; ++i) {
m_engines[i] = engines[i];
}
m_engCnt = cnt;
}
else
m_engCnt = 0;
}
Ship& Ship::operator+=(const Engine &e){
if (m_type[0] != '\0' && m_engCnt < NUM_OF_ENGINES) {
m_engines[m_engCnt] = e;
++m_engCnt;
}
return *this;
}

C++ linker undefined reference to function cannot find my error

It is a homework problem. It compiles fine, but linker gives undefined reference to my function getSalesData - line 20 just after my first for loop. Here is the code. I cannot find where I have done anything incorrectly; I have my prototype defined and it matches my function header, and I am simply calling the function.
// chips and salsa
#include <iostream>
#include <iomanip>
#include <string>
int getJarsSold(std::string type);
void getSalesData(int jarsSold[],int size,int &totalJars,int &highSeller,int &lowSeller);
int main() {
const int SIZE = 5;
const std::string salsaTypes[] {"Mild","Medium","Sweet","Hot","Zesty"};
int jarsSold[SIZE] = {};
int highIndex,lowIndex,totalJarsSold;
for (int i = 0; i < SIZE; i++) {
jarsSold[i] = getJarsSold(salsaTypes[i]);
}
getSalesData(jarsSold,SIZE,totalJarsSold,highIndex,lowIndex);
std::cout << " Type Jars Sold\n";
std::cout << "---------------------\n";
for (int i = 0; i < SIZE; i++) {
std::cout << std::setw(8) << salsaTypes[i] << std::setw(15) << jarsSold[i] << std::endl;
}
std::cout << "*********************\n";
std::cout << "Total Sales = " << totalJarsSold << std::endl;
std::cout << "Highest Seller = " << salsaTypes[highIndex] << std::endl;
std::cout << "Lowest Seller = " << salsaTypes[lowIndex] << std::endl;
}
int getJarsSold(std::string type) {
bool validData = false;
int numJars;
while (!validData) {
std::cout << "Enter jars sold this month for " << type << " salsa type: ";
std::cin >> numJars;
if (numJars < 0) {
std::cout << "Number of jars sold must be 0 or positive number.\n";
}
else {
validData = true;
}
}
validData = false;
return numJars;
}
void getSalesData(int jarsSold[],int size,int totalJars,int highIndex,int lowIndex) {
bool firstRun = true;
int highVal,lowVal;
totalJars = 0;
for (int i = 0; i < size; i++) {
if (firstRun) {
highIndex = i;
highVal = jarsSold[highIndex];
lowIndex = i;
lowVal = jarsSold[lowIndex];
totalJars += jarsSold[i];
firstRun = false;
}
else {
totalJars += jarsSold[i];
if (jarsSold[i] > highVal) {
highVal = jarsSold[i];
highIndex = i;
}
if (jarsSold[i] < lowVal) {
lowVal = jarsSold[i];
lowIndex = i;
}
}
}
}
Any help is appreciated. I am just using -c for compiling and -o for linking, nothing fancy as I know no better.

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.

Destructor problems+ list display [duplicate]

This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 7 years ago.
I have the following code:
The problem is when I create a list in main of type: Reteta.
After I display the list I receive am error of bad allocation. If I comment the destructor from the class Reteta the program works. Can you help me find the bug? Or maybe I didn't display the list well so the program have other problems to take care of.
Here is the code:
#include<iostream>
#include<fstream>
#include<list>
using namespace std;
class Medicament{
private:
char *denumire;
float pret;
public:
Medicament()
{
this->pret = 0;
this->denumire = new char[strlen("Fara denumire")];
strcpy(this->denumire, "Fara denumire");
}
Medicament(char* denumire, float pret)
{
this->denumire = new char[strlen(denumire) + 1];
strcpy(this->denumire, denumire);
this->pret = pret;
}
Medicament(const Medicament& x)
{
this->denumire = new char[strlen(x.denumire) + 1];
strcpy(this->denumire, x.denumire);
this->pret = x.pret;
}
~Medicament()
{
if (this->denumire)
{
delete[] this->denumire;
}
}
void setDenumire(char *x)
{
if (x)
{
if (this->denumire)
{
delete[] this->denumire;
}
this->denumire = new char[strlen(x) + 1];
strcpy(this->denumire, x);
}
}
char* getDenumire()
{
return this->denumire;
}
void setPret(float f)
{
if (f)
{
this->pret = f;
}
}
Medicament operator=(Medicament x)
{
this->denumire = new char[strlen(x.denumire) + 1];
strcpy(this->denumire, x.denumire);
this->pret = x.pret;
return *this;
}
friend ostream& operator<<(ostream& consola, Medicament &x)
{
consola << "Medicament: " << x.denumire << endl; //error here
consola << "Pret: " << x.pret << endl;
return consola;
}
float getPret()
{
return this->pret;
}
friend class Reteta;
};
class Reteta{
protected:
Medicament *medicamente;
int n;
public:
Reteta()
{
this->n = 0;
this->medicamente = NULL;
}
Reteta(Medicament *v, int n)
{
this->n = n;
this->medicamente = new Medicament[n];
for (int i = 0; i < n; i++)
{
this->medicamente[i] = v[i];
}
}
~Reteta()
{
if (this->medicamente)
{
delete[] this->medicamente; //The problem is here. If I comment this the program works.
}
}
int getN()
{
return this->n;
}
friend ostream& operator<<(ostream& consola, Reteta& x)
{
consola << "Numar de medicamente: " << x.n << endl;
consola << " -->Lista Medicamente<-- "<<endl;
for (int i = 0; i < x.n; i++)
{
consola << x.medicamente[i].getDenumire() <<endl; //error at this line when I compile
consola << x.medicamente[i].getPret()<< endl;
}
return consola;
}
void adaugaMedicament(Medicament x)
{
Reteta y;
y.medicamente= new Medicament[this->n+1];
for (int i = 0; i < this->n; i++)
{
y.medicamente[i] = this->medicamente[i];
}
y.medicamente[this->n] = x;
delete[] this->medicamente;
this->medicamente = new Medicament[this->n + 1];
this->n++;
for (int i = 0; i < this->n; i++)
{
this->medicamente[i] = y.medicamente[i];
}
}
Medicament operator[](int i)
{
if (i >= 0 && i < this->n)
{
return this->medicamente[i];
}
}
friend class RetetaCompensata;
virtual float getValoare()
{
float sum = 0;
for (int i = 0; i < this->n; i++)
{
sum=sum+this->medicamente[i].getPret();
}
return sum;
}
friend ifstream& operator>>(ifstream& consola, Reteta& x)
{
char aux[30];
float z;
consola >> x.n;
if (x.medicamente)
delete[] x.medicamente;
x.medicamente = new Medicament[x.n];
for (int i = 0; i < x.n; i++)
{
consola >> aux >> z;
Medicament m(aux, z);
x.medicamente[i] = m;
}
return consola;
}
};
class RetetaCompensata : public Reteta{
private:
float procentCompensat;
public:
RetetaCompensata(float procent)
{
this->procentCompensat = procent;
}
RetetaCompensata(Reteta r, float procent)
{
this->procentCompensat = procent;
this->n = r.n;
this->medicamente = new Medicament[r.n];
for (int i = 0; i < r.n; i++)
{
this->medicamente[i] = r.medicamente[i];
}
}
float getValoare()
{
float sum = 0;
sum = this->procentCompensat*this->getValoare();
return sum;
}
friend ostream& operator<<(ostream& consola, RetetaCompensata &x)
{
consola << "**Procent compensat: " << x.procentCompensat << endl;
consola << "Numar de medicamente: " << x.n << endl;
consola << " -->Lista Medicamente<-- " << endl;
for (int i = 0; i < x.n; i++)
{
consola << x.medicamente[i] << " ";
}
return consola;
}
};
void main()
{
//1
Medicament nurofen("Nurofen", 11.25f);
Medicament aspirina = nurofen;
aspirina.setDenumire("Aspirina");
aspirina.setPret(4.5f);
Medicament bixtonim("Bixtonim", 8.2f);
Medicament temp;
temp = nurofen;
cout << temp << endl;
cout << nurofen << endl;
cout << aspirina << endl;
//2
Medicament medicamente[] = { aspirina, nurofen };
Reteta r0(medicamente, 2);
cout << r0 << endl;
//3
Reteta r1;
r1.adaugaMedicament(nurofen);
r1.adaugaMedicament(aspirina);
for (int i = 0; i < r1.getN(); i++)
{
cout << r1[i] << endl;
}
//4
RetetaCompensata r2(0.5);
r2.adaugaMedicament(bixtonim);
r2.adaugaMedicament(aspirina);
RetetaCompensata r3(r1, 0.2);
cout << "AFISARE R3" << endl;
cout << r3 << endl << endl;
Reteta* p = &r1;
cout <<"Valoare reteta r1: "<< p->getValoare() << endl;
//5
Reteta r4;
ifstream fisier("retete.txt");
fisier >> r4;
cout << r4 << endl;
//6
cout << endl << "Afisare Lista :" << endl << endl << endl;
list<Reteta> R;
list<Reteta>::iterator it;
R.push_back(r0);
R.push_back(r1);
R.push_back(r3);
R.push_back(r2);
R.push_back(r4);
for (it = R.begin(); it != R.end(); it++)
{
cout << *it << " Valoare Reteta: " << it->getValoare() << endl << endl << endl; // error at this line when I compile
}
}
This is a memory overwrite:
this->denumire = new char[strlen("Fara denumire")];
strcpy(this->denumire, "Fara denumire");
You are not allocating room for the terminating null character:
this->denumire = new char[strlen("Fara denumire") + 1];
strcpy(this->denumire, "Fara denumire");
But why do this when you have std::string available? That alone not only alleviates errors like this, but you don't need to write assignment operators, copy constructor, or destructor for your Medicament class.
The other error is that your Reteta class lacks a copy constructor and assignment operator, thus it is not safely copyable due to the Medicament* member. You are then using this class as a type in std::list<Reteta>.
Since Reteta is not safely copyable, and std::list makes copies, you enter the world of undefined behavior. Thus you must provide appropriate copy / assignment operators for the Reteta class.

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...