Errors within Main program using classes - c++

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

Related

Debug Assertion Fails On Dynamic Array

So here is my working code for a simple dynamic array. This has to be a sample code for a very entry level data structure implementation:
#include <iostream>
using namespace std;
class AdvancedArray {
public:
AdvancedArray();
~AdvancedArray();
int get_size() const; // get the number of elements stored
double& at(int idx) const; // access the element at idx
void push_back(double d); // adds a new element
void remove(int idx); // remove the element at idx
void clear(); // delete all the data stored
void print() const;
private:
double* elements;
int size;
};
int main()
{
AdvancedArray* arr = new AdvancedArray();
cout << "The Array Size is: " << arr->get_size() << endl;
cout << "Pusing Values: 1.2, 2.1, 3.3, 4.5 in the Array. " << endl;
arr->push_back(1.2);
arr->push_back(2.1);
arr->push_back(3.3);
arr->push_back(4.5);
arr->print();
cout << "The Array Size is: " << arr->get_size() << endl;
cout << "The Element at Index 2 is: " << arr->at(2) << endl;
cout << "Deleting Values: 2.1 from the Array. " << endl;
arr->remove(1);
cout << "The Array Size is: " << arr->get_size() << endl;
arr->print();
cout << "Clearing the Array: " << endl;
arr->clear();
cout << "The Array Size is: " << arr->get_size() << endl;
arr->clear();
return 0;
}
AdvancedArray::AdvancedArray()
{
size = -1;
elements = new double[100]; //Maximum Size of the Array
}
AdvancedArray::~AdvancedArray()
{
delete[] elements;
}
int AdvancedArray::get_size() const
{
if(size < 0)
{
return 0;
}
return size;
}
double & AdvancedArray::at(int idx) const
{
if (idx < 100 && idx >= 0 && size > 0) {
return elements[idx];
}
cout << "Index Out of Bounds." << endl;
}
void AdvancedArray::push_back(double d)
{
if (size >= 100)
{
cout << "Overflow Condition. No More Space!" << endl;
}
else
{
elements[++size] = d;
cout << "Element Pushed In Stack Successfully!" << endl;
}
}
void AdvancedArray::remove(int idx)
{
if (size >= 100 || size < 0)
{
cout << "No Such Element Exists!" << endl;
}
else
{
for(int i = idx; i <size; i++)
{
elements[idx] = elements[idx + 1];
}
size--;
cout << "Element Deleted In Stack Successfully!" << endl;
}
}
void AdvancedArray::clear()
{
delete[] elements;
size = -1;
}
void AdvancedArray::print() const
{
cout << "[ ";
for(int i = 0; i <= size; i++)
{
cout << elements[i] << " ";
}
cout << "]" << endl;
}
So every time I try to run this I have the 2 problems:
What is wrong with my code? Why is the heap getting corrupted (I searched about the error code and that's all has to say)? Is my code doing some major access violations? I am using VS2015.
You do delete [] elements three times without setting elements to nullptr in between. That leads to undefined behavior the second time (and third) time.
When size == 99, the following piece of code attempts to access elements[100]:
if (size >= 100)
{
cout << "Overflow Condition. No More Space!" << endl;
}
else
{
elements[++size] = d;
cout << "Element Pushed In Stack Successfully!" << endl;
}
You need to change ++size to size++.

how to update individual elements in this OOP case?

I have this "movie store.cpp"
#include "List.h"
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
using namespace std;
//****************************************************************************************************
const static char* FILE_NAME = "Movies.csv";
int totalCheckedIn1 = 0;
int totalCheckedOut1 = 0;
//****************************************************************************************************
struct Movie
{
int MPAC;
int year;
int runtime;
int checkedIn;
int checkedOut;
string title;
Movie()
{
}
Movie(int m, int y, int r, int ci, int co, string t)
{
MPAC = m;
year = y;
runtime = r;
checkedIn = ci;
checkedOut = co;
title = t;
}
bool operator == (const Movie& rhs) const
{
return (MPAC == rhs.MPAC);
}
Movie& operator =(const Movie& rhs)
{
MPAC = rhs.MPAC;
year = rhs.year;
runtime = rhs.runtime;
checkedIn = rhs.checkedIn;
checkedOut = rhs.checkedOut;
title = rhs.title;
return *this;
}
friend ostream& operator <<(ostream& os, const Movie& m);
};
void setInventory(List<Movie> z, double f)
{
}
//****************************************************************************************************
ostream& operator<<(ostream& os, const Movie& m)
{
os << setw(7) << left << m.MPAC
<< setw(25) << left << m.title
<< setw(7) << left << m.year
<< setw(10) << left << m.runtime
<< setw(7) << left << m.checkedIn
<< setw(7) << left << m.checkedOut;
return os;
}
//****************************************************************************************************
void getData(List<Movie>& Movies);
void displayList(List<Movie>& Movies);
void findMovies(List<Movie> Movies);
//****************************************************************************************************
int main()
{
List<Movie> WebsterMovies;
getData(WebsterMovies);
cout << "CHECK";
displayList(WebsterMovies);
// findMovies(WebsterMovies);
setInventory(WebsterMovies, 10.5);
cout << "The following data is the updated Webster Movies store\n";
//displayList(WebsterMovies);
system("PAUSE");
return 0;
}
//****************************************************************************************************
void getData(List<Movie>& Movies)
{
ifstream infile(FILE_NAME);
if (!infile)
{
cout << "Problem opening file" << endl;
exit(99);
}
while (!infile.eof())
{
Movie m;
if (infile.peek() == EOF)
break;
infile >> m.MPAC;
infile.ignore();
infile >> m.year;
infile.ignore();
infile >> m.runtime;
infile.ignore();
infile >> m.checkedIn;
infile.ignore();
infile >> m.checkedOut;
infile.ignore();
getline(infile, m.title);
Movies.insert(m);
}
infile.close();
}
//****************************************************************************************************
void displayList(List<Movie>& Movies)
{
int totalCheckedIn = 0;
int totalCheckedOut = 0;
cout << "The Webster Movie Store list includes : " << endl;
cout << setw(7) << left << "MPAC"
<< setw(25) << left << "Title"
<< setw(7) << left << "Year"
<< setw(10) << left << "RunTime"
<< setw(7) << left << "In"
<< setw(7) << left << "Out" << endl;
cout << "-------------------------------------------------------------------------------" << endl;
double totalRunTime = 0;
for (int i = 0, size = Movies.getNumber();
i < size; ++i)
{
Movie m = Movies.getNext();
cout << m << endl;
totalRunTime += m.runtime;
totalCheckedIn += m.checkedIn;
totalCheckedOut += m.checkedOut;
}
cout << "The average run time for the " << Movies.getNumber()
<< " movies is " << fixed << setprecision(1)
<< totalRunTime / Movies.getNumber() << endl;
cout << "There are " << totalCheckedIn << " movies checked in " << endl;
cout << "There are " << totalCheckedOut << " movies checked out" << endl;
totalCheckedIn1 = totalCheckedIn;
}
//****************************************************************************************************
void findMovies(List<Movie> Movies)
{
while (true)
{
cout << "Enter the MPAC of a movie to locate:";
int input;
cin >> input;
if (input == 0)
break;
Movie m;
m.MPAC = input;
if (Movies.getMember(m))
{
cout << setw(7) << left << "MPAC"
<< setw(25) << left << "Title"
<< setw(7) << left << "Year"
<< setw(10) << left << "RunTime"
<< setw(7) << left << "In"
<< setw(7) << left << "Out" << endl;
cout << "-------------------------------------------------------------------------------" << endl;
cout << m << endl;
}
else
{
cout << "That movie is not in the store" << endl;
}
}
}
this is "list.h"
#ifndef LIST_H
#define LIST_H
#include <iostream>
//********************************************************************************
template <typename T>
class List
{
public:
List();
List(int size);
List(const List &obj);
~List();
void insert(T);
T getNext(); // Returns the next element in the array.
bool getMember(T&); // Returns true if we can find the member, false otherwise.
int getNumber(); // Returns the number of items in the list.
private:
T *pList;
int numberInList; // Number of elements in the list.
int listSize; // Size of the list.
int nextIndex; // Index that points to the next element in the array.
};
//********************************************************************************
// Default Constructor
template <typename T>
List<T>::List()
{
numberInList = 0;
listSize = 100;
nextIndex = 0;
pList = new T[listSize];
}
//********************************************************************************
// Overloaded Constructor
template <typename T>
List<T>::List(int size)
{
numberInList = 0;
listSize = size;
nextIndex = 0;
pList = new T[listSize];
}
//********************************************************************************
// Copy Constructor
template <typename T>
List<T>::List(const List &obj)
{
numberInList = obj.numberInList;
listSize = obj.listSize;
nextIndex = obj.nextIndex;
pList = new T[listSize];
for (int i = 0; i < listSize; i++)
{
pList[i] = obj.pList[i];
}
}
//********************************************************************************
// Destructor
template <typename T>
List<T>::~List()
{
delete[]pList;
}
//********************************************************************************
template <typename T>
void List<T>::insert(T item)
{
int temp = numberInList++;
pList[temp] = item;
}
//********************************************************************************
template <typename T>
T List<T>::getNext()
{
return pList[nextIndex++];
}
//********************************************************************************
template <typename T>
bool List<T>::getMember(T& item)
{
for (int i = 0; i < numberInList; ++i)
{
if (item == pList[i])
{
item = pList[i];
return true;
}
}
return false;
}
//********************************************************************************
template <typename T>
int List<T>::getNumber()
{
return numberInList;
}
#endif
Problem i have is that setInventory function needs to update the checkedIn member of each list element using the formula (CheckedIn + CheckedOut) * ( f /100.0). Can someone guide me how can i update individual element using this function.help i got said" In order to update each element of the List, you need modify the template to include a setItem function that sets the associated element in the List object to the item that is passed to the setItem function. HINT: This function should only contain one C++ statement."
if someone can guide me syntax of how i can update individual elements.
this is something i wrote for setInventory()
void setInventory(List<Movie> WebsterMovies , double f)
{
Movie m = WebsterMovies.getNext();
cout << m << endl;
cout << "Check again" << endl << endl;
int size = WebsterMovies.getNumber();
int increment = 0;
for (int i = 0 ; i < size; ++i)
{
cout << m << endl;
increment = trunc(((m.checkedIn + m.checkedOut) * f )/ 100);
m.checkedIn = m.checkedIn + increment;
cout << "updated checkin is : " << m.checkedIn << endl;
WebsterMovies.setItem(m);
Movie m = WebsterMovies.getNext();
}
}
this is setItem i wrote
template <typename T>
void List<T>::setItem(T item)
{
pList[numberInList] = item;
}
p.s beginner here so sorry for bad English or any other mistake.
To update an element in a container, such as std::list, you need to find the element, then update the fields.
An example:
std::list<Movie> database;
// Search by title
std::list<Movie>::iterator iter;
const std::list<Movie>::iterator end_iter = database.end();
for (iter = database.begin();
iter != end_iter;
++iter)
{
if (iter->title == search_title)
{
Update_Movie(*iter);
}
}

C++ Hamming Function

This program is supposed to create three arrays of class object My_array. The first array is filled with random numbers. The second array is an exact copy of the first. The third array is entered by the user. The program checks to make sure that the first two arrays indeed equal each other and then it check to the hamming distance of the first and third array. The professor defines the hamming distance as each part off the array that is different.
My problem has been getting hamming to work. I actually have a hard time with operating overloading so I am surprised that works (well I have no errors showing in VS Studio) but not the hamming part. Any help would be appreciated. There are three files in order: main.cpp, my_array.cpp, and my_array.h. Function definitions and declarations were provided by professor. I am required to insert how each function operates.
#include "my_array.h"
#include <iostream>
using namespace std;
int main()
{
int size;
cout << "How big of an array shall we work with? ";
cin >> size;
My_array a(size);
My_array b(size);
My_array c(size);
a.randomize(100);
b = a;
c.input();
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << "a != b: " << (a != b) << endl;
cout << "a == b: " << (a == b) << endl;
cout << "The hamming distance is: " << a.hamming(c);
return 0;
}
#include "my_array.h"
#include <iostream>
using namespace std;
#include <stdlib.h>
#include <time.h>
// Constructor
My_array::My_array(int the_size)
{
array = NULL;
size = 0;
resize(the_size);
}
// Destructor.
My_array::~My_array()
{
empty();
}
// Copy constructor
My_array::My_array(My_array &data)
: size(data.size)
{
array = new int[size];
for (int i = 0; i<size; i++)
array[i] = data.array[i];
}
// Overloaded assignment operator.
My_array &My_array::operator=(My_array &data)
{
if (this != &data) {
resize(data.size);
for (int i = 0; i<size; i++)
array[i] = data.array[i];
}
else
cout << "Attempt to copy an object on itself. "
<< "Operation ignored." << endl;
return *this;
}
void My_array::input()
{
int j;
cout << "Please enter " << size << " numbers.\n";
for (int i = 0; i < size; i++)
{
cout << "Number " << i + 1 << ": ";
cin >> j;
array[i] = j;
}
}
void My_array::randomize(int limit)
{
srand(time(NULL));
for (int i = 0; i < size; i++)
array[i] = rand() % limit + 1;
}
bool My_array::operator ==(My_array &data)
{
if(this->size != data.size)
return false;
for (int i = 0; i <size; i++)
{
if (*this[i].array != data.array[i])
return false;
}
return true;
}
bool My_array::operator !=(My_array &data)
{
if (*this == data)
return false;
return true;
}
int My_array::hamming(My_array &data)
{
int ham = 0;
for (int i = 0; i < size; i++)
if (*this[i].array != data[i].array)
ham++;
return ham;
}
// This function will empty the target object
void My_array::empty()
{
if (size != 0 && array != NULL) {
size = 0;
delete[] array;
}
}
// Resize the array.
void My_array::resize(int the_size)
{
if (size >= 0) {
empty();
if (the_size != 0) {
size = the_size;
array = new int[size];
}
}
else
cout << "Resize attepmted with a negative size. "
<< "Operation ignored." << endl;
}
// Access an element of the array.
int &My_array::operator[](int index)
{
if (index < size)
return array[index];
else {
cerr << "Illegal access to an element of the array." << endl
<< "The size of the array was " << size
<< " and the index was " << index << endl;
exit(1);
}
}
// Accessor
int My_array::get_size()
{
return size;
}
void My_array::output()
{
cout << "The array of size " << size
<< " contains the elements:" << endl;
for (int i = 0; i<size; i++)
cout << array[i] << ' ';
cout << endl;
}
//overloading the << operator.
ostream &operator<<(ostream &out, My_array &data)
{
out << "The array of size " << data.size
<< " contains the elements:" << endl;
for (int i = 0; i<data.size; i++)
out << data.array[i] << ' ';
out << endl;
return out;
}
#ifndef MY_ARRAY_H
#define MY_ARRAY_H
#include <iostream>
using namespace std;
class My_array {
protected:
int size;
int *array;
public:
// Constructor
My_array(int the_size = 0);
// Destructor
~My_array();
// Copy constructor
My_array(My_array &data);
// Assignment operator
My_array &operator=(My_array &data);
void input();
void randomize(int limit);
bool operator ==(My_array &data);
bool operator !=(My_array &data);
int hamming(My_array &data);
// Deletes the array
void empty();
// Resize the array.
void resize(int the_size = 0);
// Access an element of the array.
int &operator[](int index);
// Returns the size of the array.
int get_size();
// Output the elements of the array.
void output();
friend ostream &operator<<(ostream &out, My_array &data);
};
#endif
This:
*this[i].array != data[i].array
should be this:
array[i] != data.array[i]
or this:
array[i] != data[i]
The *this is unnecessary, and data[i] is a reference to an int (the same one you get by calling data.array[i], thanks to your operator[]), and an int has no member called "array".

Can't pass array values to a vector from within a constructor

I'm at a bit of a roadblock and I just can't seem to figure out where I went wrong. Essentially, I just want to pass the values from the array in the test code to a vector via constructor and then print the contents of the vector. For whatever reason, I can't even hit the for loop that starts to add the array values to the vector.
header code:
#pragma once
#ifndef BoxOfProduce_H
#define BoxOfProduce_H
#include <vector>
#include <iostream>
#include <cstdlib> //for exit
using namespace std;
class BoxOfProduce
{
public:
BoxOfProduce();
BoxOfProduce(string customerId, int size, bool doRandom, bool okDuplicates, std::string productList[], int listSize);
void addBundle(string productList);
void displayBox();
private:
string customerID;
vector<string> test;
vector<string> bundles;
bool allowDuplicates;
bool buildRandom;
int size;
};
#endif
// End of dayOfYear.h
BocOfProduce.cpp
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <cstdlib> //for exit
using namespace std;
#include "BoxOfProduce.h"
vector<string> tempbundles;
bool isInVect = false;
BoxOfProduce::BoxOfProduce()
{
customerID = "No Name";
allowDuplicates = true;
buildRandom = false;
}
BoxOfProduce::BoxOfProduce(string customerId, int size, bool doRandom, bool okDuplicates, string productList[], int listSize)
{
customerID = customerId;
buildRandom = doRandom;
allowDuplicates = okDuplicates;
size = size;
for (int k = 0; k > listSize; k++)
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
if (allowDuplicates == false)
{
for (int k = 0; k > listSize; k++)
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
for (int i = 0; i < listSize; i++)
{
for (int j = 0 + 1; j < listSize; j++)
{
if (tempbundles[i] == bundles[j])
{
isInVect = true;
}
if (isInVect == false)
{
bundles.push_back(tempbundles[i]);
cout << "added to isinvect bundle" << endl;
}
}
}
}
else if (allowDuplicates == true)
{
for (int k = 1; k > listSize; k++)
{
bundles.push_back(productList[k]);
cout << "added to normal bundle" << endl;
}
}
}
void BoxOfProduce::addBundle(string productList)
{
for (int k = 1; k > 100; k++)
{
bundles.push_back(productList);
}
}
void BoxOfProduce::displayBox()
{
cout << "custome ID is: " << customerID << "\n" << endl;
std::cout << std::boolalpha;
cout << "-buildRandom set to " << buildRandom << endl;
cout << "-allowDuplicates set to " << allowDuplicates << endl;
cout << "Contents of box: " << customerID << " with size: " << size << endl;
test.push_back("test");
for (int i = 0; i < bundles.size(); i++)
{
cout << bundles[i] << "\n";
}
cout << "\n" << endl;
}
Test code:
#include <iostream>
#include <string>
#include <iterator>
#include <vector>
#include <algorithm>
#include <cstdlib> //for exit
#include "BoxOfProduce.h"
using namespace std;
int main()
{
srand(1234); // Seed random generator for random additions of products
const int LISTSIZE = 12;
string produceList[] = { "Broccoli", "Tomato", "Kiwi", "Kale", "Tomatillo",
"Mango", "Spinach", "Cucumber", "Radish", "Chard", "Spinach", "Mango" };
cout << "Original list of produce:" << endl;
for (int i = 0; i < LISTSIZE; i++)
{
cout << "item[" << i << "] = " << produceList[i] << endl;
}
// Test BoxOfProduce class
cout << endl << "Start with empty box0" << endl;
BoxOfProduce box0; // Default constructor creates empty box
cout << "Display box0:" << endl;
box0.displayBox(); // Display the empty box
cout << endl; // Skip a line
cout << "Add all products from the produceList[] to box0 allowing duplicates:"
<< endl;
for (int i = 0; i < LISTSIZE; i++)
box0.addBundle(produceList[i]); // Duplicates allowed in box
cout << "Display box0 again after loading with products:" << endl;
box0.displayBox();
cout << endl;
BoxOfProduce box1("Box-1", 4, false, true, produceList, LISTSIZE);
box1.displayBox();
BoxOfProduce box2("Box-2", 4, true, false, produceList, LISTSIZE);
box2.displayBox();
BoxOfProduce box3("Box-3", 8, true, true, produceList, LISTSIZE);
box3.displayBox();
BoxOfProduce box4("Box-4", 12, true, true, produceList, LISTSIZE);
box4.displayBox();
BoxOfProduce box5("Box-5", 12, true, false, produceList, LISTSIZE);
box5.displayBox(); // This box produces an error message
}
Thank you for any and all help!
your problem is that in case of duplicate you use the list size for bundle and tempbundle which is not the case this should fix check the code for BocOfProduce.cpp
vector<string> tempbundles;
bool isInVect = false;
BoxOfProduce::BoxOfProduce()
{
customerID = "No Name";
allowDuplicates = true;
buildRandom = false;
}
BoxOfProduce::BoxOfProduce(string customerId, int size, bool doRandom, bool okDuplicates, string productList[], int listSize)
{
customerID = customerId;
buildRandom = doRandom;
allowDuplicates = okDuplicates;
size = size;
tempbundles = vector<int>() ; // set temp bundles to empty vector
for (int k = 0; k < listSize; k++) //k was >listSize it should be <
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
if (allowDuplicates == false)
{
for (int k = 0; k < listSize; k++)
{
tempbundles.push_back(productList[k]);
cout << "added to temp" << endl;
}
for (int i = 0; i < listSize; i++)
{
isInVect = false;
for (int j = 0 + 1; j < bundles.size(); j++)
{
if (tempbundles[i] == bundles[j])
{
isInVect = true;
}
}
if (isInVect == false)
{
bundles.push_back(tempbundles[i]);
cout << "added to isinvect bundle" << endl;
}
}
}
else if (allowDuplicates == true)
{
for (int k = 1; k < listSize; k++)
{
bundles.push_back(productList[k]);
cout << "added to normal bundle" << endl;
}
}
}
void BoxOfProduce::addBundle(string productList)
{
for (int k = 1; k > 100; k++)
{
bundles.push_back(productList);
}
}
void BoxOfProduce::displayBox()
{
cout << "custome ID is: " << customerID << "\n" << endl;
std::cout << std::boolalpha;
cout << "-buildRandom set to " << buildRandom << endl;
cout << "-allowDuplicates set to " << allowDuplicates << endl;
cout << "Contents of box: " << customerID << " with size: " << bundles.size() << endl;
test.push_back("test");
for (int i = 0; i < bundles.size(); i++)
{
cout << bundles[i] << "\n";
}
cout << "\n" << endl;
}

Changing an array class to hold a dynamic array

everything i have read says this should be easy and that you just add these three lines
typedef double* DoublePtr;
DoublePtr p;
p = new double [10]
but where do i add this code? Everything i have tried just breaks my program what am I missing? I tried a set function to set the value of max size but it didn't work either
does anyone know how to do this?
#include<iostream>
using namespace std;
const int MAX_SIZE = 50;
class ListDynamic
{
public:
ListDynamic();
bool full();
int getSize();
void addValue(double value);
double getValue(int index);
double getLast();
void deleteLast();
friend ostream& operator <<(ostream& out, const ListDynamic& thisList);
private:
double listValues[MAX_SIZE];
int size;
};
int main()
{
double value;
ListDynamic l;
cout << "size of List " << l.getSize() << endl;
cout << "New size of List " << l.getSize() << endl;
cout << "First Value: " << l.getValue(0) << endl;
cout << "Last Value: " << l.getLast() << endl;
cout << "deleting last value from list" << endl;
l.deleteLast();
cout << "new list size " << l.getSize() << endl;
cout << "the list now contains: " << endl << l << endl;
system("pause");
return 0;
}
ListDynamic::ListDynamic()
{
size = 0;
}
bool ListDynamic::full()
{
return (size == MAX_SIZE);
}
int ListDynamic::getSize()
{
return size;
}
void ListDynamic::addValue(double value)
{
if (size < MAX_SIZE)
{
listValues[size] = value;
size++;
}
else
cout << "\n\n*** Error in ListDynamic Class: Attempting to add value past max limit.";
}
double ListDynamic::getValue(int index)
{
if (index < size)
return listValues[index];
else
cout << "\n\n*** Error in ListDynamic Class: Attempting to retrieve value past current size.";
}
double ListDynamic::getLast()
{
if (size > 0)
return getValue(size - 1);
else
cout << "\n\n*** Error in ListDynamic Class: Call to getLast in Empty List.";
}
void ListDynamic::deleteLast()
{
if (size > 0)
size--;
else
cout << "\n\n*** Error in ListDynamic Class: Call to deleteLast in Empty List.";
}
ostream& operator <<(ostream& out, const ListDynamic& thisList)
{
for (int i = 0; i < thisList.size; i++)
out << thisList.listValues[i] << endl;
return out;
}
You need to change listValues to a double*
double* listValues;
And when you add a value greater than the size, you'll need to reallocate the array your array and copy the elements of the former array to the new one. For example:
void ListDynamic::addValue(double value)
{
if (full())
{
double* temp = new double[size];
std::copy(listValues, listValues + size, temp);
delete[] listValues;
listValues = new double[size + 1];
std::copy(temp, temp + size, listValues);
listValues[size] = value;
delete[] temp;
} else
{
listValues[size++] = value;
}
}