in my C++ class we are finally getting conceptually fairly deep (well, relatively!) and I'm struggling with building a class from a previous class.
Here is my first class header, which builds partially filled array objects. To my knowledge, it is fully functional:
#ifndef PARTIALARRAY_H
#define PARTIALARRAY_H
#include <iostream>
#include <string.h>
using namespace std;
typedef int ITEM_TYPE;
ITEM_TYPE const MAX = 50;
class PartialArray
{
public:
//-----------------------------------------ctors:-----------------------------------------
PartialArray();
PartialArray(const int init[], int used);
//-----------------------------------------member functions:-----------------------------------------
void PrintArray();
int Search(ITEM_TYPE key);
int Append(ITEM_TYPE appendMe);
int ShiftRight(int shiftHere);
int ShiftLeft(int shiftHere);
int InsertBefore(ITEM_TYPE insertThis, int insertHere);
int InsertAfter(ITEM_TYPE insertThis, int insertHere);
int Delete(int deleteHere);
void DeleteRepeats();
int NumUsed();
void Sort();
void Reverse();
string ErrorDescr(int failCode);
//-----------------------------------------operators:-----------------------------------------
ITEM_TYPE& operator [] (ITEM_TYPE x);
private:
//-----------------------------------------member vars:-----------------------------------------
ITEM_TYPE a[MAX];
int numUsed;
};
#endif // PARTIALARRAY_H
And here are the class functions:
#include "partialarray.h"
#include <iostream>
#include <string.h>
using namespace std;
//-----------------------------------------ctors:-----------------------------------------
PartialArray::PartialArray()
{
numUsed=0;
}
PartialArray::PartialArray(const int init[], int used)
{
numUsed = used;
for(int i=0; i<numUsed; i++)
{
a[i]=init[i];
}
}
//-----------------------------------------member functions:-----------------------------------------
//Prints the array up to its last used element
void PartialArray::PrintArray()
{
for(int i=0; i<numUsed; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
//Searches the array for a particular value and returns the index at which the value first appears
int PartialArray::Search(ITEM_TYPE key)
{
for(int i=0; i<numUsed; i++)
{
if(a[i]==key)
return i;
}
return -1;
}
//Takes a number and appends it to the end of the array after the last interesting element
int PartialArray::Append(ITEM_TYPE appendMe)
{
if(numUsed<MAX)
a[numUsed++] = appendMe;
else
return 1;
return 0;
}
//Shifts all elements of the array to the right starting at a particular index
int PartialArray::ShiftRight(int shiftHere)
{
if(shiftHere<numUsed)
{
ITEM_TYPE save = a[numUsed-1];
for(int i=numUsed; i>=shiftHere; i--)
{
a[i] = a[i-1];
}
a[shiftHere] = save;
return 0;
}
else
return 2;
}
//Shifts all elements of the array to the left starting at a particular index
int PartialArray::ShiftLeft(int shiftHere)
{
if(shiftHere<numUsed)
{
ITEM_TYPE save = a[shiftHere];
for(int i=shiftHere; i<numUsed; i++)
{
a[i] = a[i+1];
}
a[numUsed-1] = save;
return 0;
}
else
return 2;
}
//Takes a number and a position and inserts the number before that position in the array shifting the elements to the right
int PartialArray::InsertBefore(ITEM_TYPE insertThis, int insertHere)
{
if(insertHere>numUsed)
return 2;
else
{
numUsed++;
ShiftRight(insertHere);
a[insertHere] = insertThis;
}
return 0;
}
//Takes a number and a position and inserts the number after that position in the array shifting the elements to the right
int PartialArray::InsertAfter(ITEM_TYPE insertThis, int insertHere)
{
if(insertHere>numUsed)
return 2;
else if(numUsed>=MAX)
return 1;
else
{
numUsed++;
ShiftRight(insertHere+1);
a[insertHere+1] = insertThis;
}
return 0;
}
//Takes a position and removes that item from the array, shifting all the elements to the left
int PartialArray::Delete(int deleteHere)
{
if(deleteHere <= numUsed)
{
ShiftLeft(deleteHere);
numUsed--;
return 0;
}
else
return 2;
}
//Deletes repeated elements in the array and replaces the with 0
void PartialArray::DeleteRepeats()
{
for(int i=0;i<numUsed;i++)
{
ITEM_TYPE n=a[i];
for(int j=i+1; j<numUsed;j++)
{
if(n == a[j])
{
Delete(j);
j--;
}
}
}
}
//Returns number of interesting elements in the array
int PartialArray::NumUsed()
{
return numUsed;
}
//Utilizes a bubble sort algorithm
void PartialArray::Sort()
{
bool swap = true;
int j = 0;
int save;
while (swap==true)
{
swap = false;
j++;
for (int i = 0; i < numUsed - j; i++)
{
if (a[i] > a[i + 1])
{
save = a[i];
a[i] = a[i + 1];
a[i + 1] = save;
swap = true;
}
}
}
}
void PartialArray::Reverse()
{
for(int i=0;i<numUsed-1;i++)
{
ITEM_TYPE save = a[numUsed-1];
ShiftRight(i);
a[i] = save;
}
}
//Returns the appropriate error description for a particular fail code
string PartialArray::ErrorDescr(int failCode)
{
switch(failCode)
{
case -1:
return "ERROR: item not found";
break;
case 1:
return "ERROR: array is full";
break;
case 2:
return "ERROR: unused index";
break;
default:
return "UNKNOWN ERROR";
break;
}
}
//-----------------------------------------operators:-----------------------------------------
ITEM_TYPE& PartialArray::operator [](ITEM_TYPE x)
{
return a[x];
}
Now, here is where things have gotten tricky. To build the two dimensional array class, I'm supposed to create an array of arrays. I'm at a loss as to how I should go about this, and after tinkering and googling for a few hours I've only become more confused. Specifically, the <<, [], and [](constant version) operators and the TwoDArray constructor have thrown me for a loop, and I'm stuck without much sense of what to do next. Here is the TwoD header file:
#ifndef TWODARRAY_H
#define TWODARRAY_H
#include "partialarray.h"
#include <iostream>
#include <string.h>
typedef int ITEM_TYPE;
class TwoDArray
{
friend ostream& operator << (ostream &outs, const TwoDArray& printMe);
public:
//ctors:
TwoDArray();
//member functions:
//PartialArray& operator [](int index); //[ ] operator for the TwoDArray object
//PartialArray operator [](int index) const; //[ ] operator for the TwoDArray object (const version)
int Append(int appendMe, int row);
int InsertBefore(int insertMe, int row, int column);
int InsertAfter(int insertMe, int row, int column);
int Delete(int row, int column);
bool Search(ITEM_TYPE key, int &row, int &column);
private:
//member vars:
PartialArray a[MAX];
};
#endif // TWODARRAY_H
And this is what I've tried to define thus far:
TwoDArray::TwoDArray()
{
const int array0[]= {0};
PartialArray array(array0, MAX);
}
ostream& operator << (ostream &outs, const TwoDArray& printMe)
{
for(int i=0;i<MAX;i++)
{
outs << printMe.a[i];
}
return outs;
}
Ideally, the << operator will print an m by n array of items.
Related
This is a Stack class based on a dynamic array of struct for Depth First Search (DFS). The program is not able to run whenever it encounters the function, push(), which shows that the array is not successfully initialized in the constructor.
I have tried to look for the error and even changing the dynamic array of struct into parallel arrays but it still does not work. I apologize if the problem seems to be too simple to be solved as I do not have a strong foundation in C++.
#include <iostream>
#include <iomanip>
#ifndef HEADER_H
#define HEADER_H
using namespace std;
struct Value
{
int row; // row number of position
int col; // column number of position
//operator int() const { return row; }
};
class ArrayStack
{
public:
int top;
Value* array;
ArrayStack();
bool isEmpty();
bool isFull();
void push(int r, int c);
void pop();
int poprowvalue(int value);
int popcolvalue(int value);
int peekrow(int pos);
int peekcol(int pos);
int count();
void change(int pos, int value1, int value2);
void display();
void resize();
private:
int size;
};
ArrayStack::ArrayStack()
{
//Initialize all variablies
top = -1;
size = 10;
Value * array = new Value[size];
for (int i = 0; i < size; i++)
{
array[i].row = 0;
array[i].col = 0;
}
}
bool ArrayStack::isEmpty()
{
if (top == -1)
return true;
else
return false;
}
bool ArrayStack::isFull()
{
if (top == size - 1)
return true;
else
return false;
}
void ArrayStack::resize()
{
if (isFull())
size *= 2;
else if (top == size / 4)
size /= 2;
}
void ArrayStack::push(int r, int c)
{
if (isEmpty() == false)
resize();
array[top + 1].row = r;
array[top + 1].col = c;
top++;
}
void ArrayStack::pop()
{
int value;
if (isEmpty())
{
cout << "Stack underflow" << endl;
}
else
{
poprowvalue(array[top].row);
popcolvalue(array[top].col);
array[top].row = 0;
array[top].col = 0;
top--;
}
}
int ArrayStack::poprowvalue(int v)
{
return v;
}
int ArrayStack::popcolvalue(int v)
{
return v;
}
int ArrayStack::peekrow(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].row;
}
int ArrayStack::peekcol(int pos)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
return array[pos].col;
}
int ArrayStack::count()
{
return (top + 1);
}
void ArrayStack::change(int pos, int value1, int value2)
{
if (isEmpty())
cout << "Stack underflow" << endl;
else
{
array[pos].row = value1;
array[pos].col = value2;
}
}
void ArrayStack::display()
{
for (int i = size - 1; i > -1; i--)
{
cout << array[i].row << " " << array[i].col << endl;
}
}
#endif
I expect it to run well but an exception is always thrown on line 80, which is as follows:
Exception thrown at 0x00007FF6A160487C in Assignment1.exe: 0xC0000005: Access violation writing location 0x0000000000000000.
The problem is this line right here:
Value * array = new Value[size];
This declares a new array variable. You are allocating that array instead, and not your member variable array.
The answer is simple, just change it to this instead:
array = new Value[size];
I was assigned to create a chained hash table using a vector of vectors. It is designed to hold objects of type Entry. I have written all of the functions and the constructor but when I try to use the constructor that reads an input and then output it back to me in order of keys, whichever string was on the last line of the .txt file its reading from is gone. I think its a problem with my constructor because when I try to use get to get that specific value from the table before printing it its gone. I was hoping for some insight to where I might be going wrong from someone with a little more experience. Thanks. Heres my code:
Entry Header File:
#ifndef entry_h
#define entry_h
// entry.h - defines class Entry
#include <string>
#include <iosfwd>
class Entry {
public:
// constructor
Entry(unsigned int key = 0, std::string data = "");
// access and mutator functions
unsigned int get_key() const;
std::string get_data() const;
static unsigned int access_count();
void set_key(unsigned int k);
void set_data(std::string d);
// operator conversion function simplifies comparisons
operator unsigned int () const;
// input and output friends
friend std::istream& operator>>
(std::istream& inp, Entry &e);
friend std::ostream& operator<<
(std::ostream& out, Entry &e);
private:
unsigned int key;
std::string data;
static unsigned int accesses;
};
#endif /* entry_h */
Table header file:
//
// table.h
//
//
#ifndef table_h
#define table_h
#include <string>
#include <vector>
#include <algorithm>
#include "entry.h"
using namespace std;
class Table {
public:
Table(unsigned int max_entries = 100);
//Builds empty table to hold 100 entries
Table(unsigned int entries, std::istream& input);
//Builds table to hold entries, reads and puts them 1 at a time
~Table();
//Destructor
void put(unsigned int key, std::string data);
//Creates new entry for the table
//Updates if key is used
void put(Entry e);
//Creates a copy of e in the table
string get(unsigned int key) const;
//Returns string associated with key
//Returns empty string if key isnt used
bool remove(unsigned int key);
//Removes entry in given key
//Returns true of removed, false of no entry
int find(Entry e);
//index in second array that e exists, 0 if not found
friend std::ostream& operator<< (std::ostream& out, const Table& t);
//Prints each entry in the table in order of their key
private:
int size;
int num_entries;
unsigned int hashkey(unsigned int key) const;
vector<vector<Entry> > A;
};
#endif /* table_h */
Table Implementation File:
//table.cpp
#include<iostream>
#include<vector>
#include<algorithm>
#include "table.h"
using namespace std;
Table::Table(unsigned int max_entries){
max_entries = 100;
size = max_entries * 2;
A.resize(size);
}
Table::Table(unsigned int entries, std::istream& input){
size = entries*2;
A.resize(size);
num_entries = entries;
Entry temp;
for (size_t i = 0; i < entries; i++) {
input >> temp;
put(temp);
}
}
Table::~Table() {
A.clear();
}
void Table::put(unsigned int key, std::string data){
Entry e;
e.set_key(key);
e.set_data(data);
put(e);
num_entries++;
}
void Table::put(Entry e) {
if (A[hashkey(e.get_key())].empty()) {
A[hashkey(e.get_key())].push_back(e);
}
else {
for(size_t i = 0; i < A[hashkey(e.get_key())].size(); i++) {
if (A[hashkey(e.get_key())][i].get_key() == e.get_key()) {
remove(A[hashkey(e.get_key())][i].get_key());
break;
}
}
A[hashkey(e.get_key())].push_back(e);
}
}
string Table::get(unsigned int key) const {
if( A[hashkey(key)].size() == 0) {
return "";
}
else {
for (size_t i = 0; i < A[hashkey(key)].size(); i++) {
if (A[hashkey(key)][i].get_key() == key) {
return A[hashkey(key)][i].get_data();
}
else {
return "";
}
}
}
}
bool Table::remove(unsigned int key) {
for (size_t i = 0; i < A[hashkey(key)].size(); i++) {
if (A[hashkey(key)][i].get_key() == key) {
swap(A[hashkey(key)][i],A[hashkey(key)][A[hashkey(key)].size() - 1]);
A[hashkey(key)].pop_back();
num_entries--;
return true;
}
else {
return false;
}
}
}
int Table::find(Entry e) {
for (size_t i = 0; i < A[hashkey(e.get_key())].size(); i++) {
if (A[hashkey(e.get_key())][i] == e) {
return i;
}
else {
return 0;
}
}
}
ostream& operator << (ostream& out, const Table& t) {
vector<Entry> order;
for(size_t i = 0; i < t.A.size(); i++) {
for (size_t j = 0; j < t.A[i].size(); j++) {
order.push_back(t.A[i][j]);
}
}
sort(order.begin(), order.end());
for(Entry k: order) {
out << k << endl;
}
return out;
}
unsigned int Table::hashkey(unsigned int key) const{
const double c = 1.61803;
// return key % size;
return (int)(size*((key * c) - (int)(key * c)));
}
In the code shown below, in the function void printExpensiveThanT(..) i'm supposed to print out the destination, distance and the price for the offers which are more expensive than the offer T in the function, sorted in ascending order by the distance value.
I'm not sure what should i use to sort them, i experimented something with vectors but it didn't work out so i deleted it.
Any help would be appreciated.
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
class Transport {
protected:
char destination[100];
int basePrice;
int distance;
public:
Transport() {}
Transport(char *destination, int basePrice, int distance) {
strcpy(this->destination, destination);
this->basePrice = basePrice;
this->distance = distance;
}
virtual ~Transport() {}
virtual int priceTransport() = 0;
friend bool operator<(const Transport &t1, const Transport &t2) {
return t1.distance<t2.distance;
}
int getDistance(){ return distance; }
char *getDestination() { return destination; }
int getPrice() { return basePrice; }
};
class AutomobileTransport : public Transport {
private:
bool ifDriver;
public:
AutomobileTransport() {}
AutomobileTransport(char *destination, int basePrice,int distance, bool ifDriver) : Transport(destination,basePrice,distance) {
this->ifDriver = ifDriver;
}
void setIfDriver(bool ifDriver) {
this->ifDriver = ifDriver;
}
bool getIfDriver() {
return ifDriver;
}
int priceTransport() {
if(ifDriver) {
basePrice+=basePrice*20/100;
}
return basePrice;
}
friend bool operator<(const AutomobileTransport &a1, const AutomobileTransport &a2) {
return a1.distance<a2.distance;
}
};
class VanTransport: public Transport {
private:
int passengers;
public:
VanTransport() {}
VanTransport(char *destination, int basePrice, int distance, int passengers) : Transport(destination, basePrice, distance) {
this->passengers = passengers;
}
void setPassengers(int passengers) {
this->passengers = passengers;
}
int getPassengers() {
return passengers;
}
int priceTransport() {
for(int i = 0; i < passengers; i++) {
basePrice-=200;
}
return basePrice;
}
friend bool operator<(const VanTransport &k1, const VanTransport &k2) {
return k1.distance<k2.distance;
}
};
void printExpensiveThanT(Transport **offers,int n,AutomobileTransport &T) {
Transport *tmp;
for(int i = 0; i <= n; i++){
if(offers[i]->priceTransport() > T.priceTransport())
cout<<offers[i]->getDestination()<<" "<<offers[i]->getDistance()<<" "<<offers[i]->getPrice()<<endl;
}
}
int main() {
char destination[20];
int type,price,distance,passengers;
bool driver;
int n;
cin>>n;
Transport **offers;
offers=new Transport *[n];
for (int i=0; i<n; i++) {
cin>>type>>destination>>price>>distance;
if (type==1) {
cin>>driver;
offers[i]=new AutomobileTransport(destination,price,distance,driver);
} else {
cin>>passengers;
offers[i]=new VanTransport(destination,price,distance,passengers);
}
}
AutomobileTransport at("Ohrid",2000,600,false);
printExpensiveThanT(offers,n,at);
for (int i=0; i<n; i++) delete offers[i];
delete [] offers;
return 0;
}
Since you're dealing with pointers, the easiest thing to do is to use std::vector and std::sort:
#include <vector>
//...
void printExpensiveThanT(Transport **offers, int n, AutomobileTransport &T)
{
std::vector<Transport*> sortedVect;
for (int i = 0; i < n; i++)
{
if (offers[i]->priceTransport() > T.priceTransport())
sortedVect.push_back(offers[i]); // add this item to the vector
}
// sort the vector based on the dereferenced pointers and their respective
// operator <
std::sort(sortedVect.begin(), sortedVect.end(),
[](Transport* left, Transport* right) { return *left < *right; });
// print out the values
for (auto it : sortedVect)
cout << (*it).getDestination() << " " << (*it).getDistance() << " " << (*it).getPrice() << "\n";
}
Also, your original code looped one more than it should (i <= n was wrong).
Edit:
If your compiler doesn't support the C++ 11 syntax, here is an alternate solution:
#include <vector>
//...
bool Sorter(Transport* left, Transport* right)
{ return *left < *right; }
void printExpensiveThanT(Transport **offers, int n, AutomobileTransport &T)
{
std::vector<Transport*> sortedVect;
for (int i = 0; i < n; i++)
{
if (offers[i]->priceTransport() > T.priceTransport())
sortedVect.push_back(offers[i]); // add this item to the vector
}
// sort the vector based on the dereferenced pointers and their respective
// operator <
std::sort(sortedVect.begin(), sortedVect.end(), Sorter);
// print out the values
std::vector<Transport*>::iterator it = sortedVect.begin();
while (it != sortedVect.end())
{
cout << (*it).getDestination() << " " << (*it).getDistance() << " " << (*it).getPrice() << "\n";
++it;
}
}
I am writing this program for college and keep having problems with it. I wrote in using codeblocks in ubuntu and it runs fine no errors or anything. But when I run it in windows on codeblocks it crashes and I keep getting the same error "terminate called after throwing an instance of 'std::bad_alloc' what<>: std::badalloc' then it stops working.
Any help would be appreciated!
Thankyou
Ron
main.cpp
#include <iostream>
#include "set.h"
using namespace std;
int main()
{
Set Set1;
List List1;
List1.header();
int choice = 0;
int value = 0;
cout<<"Press 1 to use a list or press 2 for a set"<<endl;
cin>>choice;
if(choice == 1) //List
{
while(choice != 4)
{
value = 0;
List1.menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"Please enter value"<<endl;
cin>>value;
List1.set_value(value);
break;
case 2:List1.print_list();
break;
case 3:List1.test_copy_constructor();
break;
}
}
}
else if(choice == 2) //Set
{
while(choice != 4)
{
value = 0;
List1.menu();
cin>>choice;
switch(choice)
{
case 1:cout<<"Please enter value"<<endl;
cin>>value;
Set1.set_value(value);
break;
case 2:Set1.print_list();
break;
case 3:Set1.test_copy_constructor();
break;
}
}
}
else
{
cout<<"Please Enter a valid option"<<endl;
}
return 0;
}
set.cpp
#include "set.h"
#include <iostream>
#include <string>
using namespace std;
//Constructor
List::List()
{
int array_size;
int *array = new int[array_size];
// delete [] array;
}
List List1;
//Print functions
void List::header(void) const
{
cout<<"Program Name: Program 2"<<endl;
cout<<"Program Created: March 20,2014"<<endl;
cout<<"Created by: Ron Miller"<<endl;
cout<<"--------------------------------"<<endl;
cout<<" "<<endl;
}
void List::menu(void) const
{
cout<<" Menu"<<endl;
cout<<"---------------------------------------------------------"<<endl;
cout<<"1. Insert (value to be inserted is entered from keyboard)"<<endl;
cout<<"2. Print List (all values, one per line)"<<endl;
cout<<"3. Test Copy Constructor (pass list by value to a function"<<endl;
cout<<" and from within the function change all values in list"<<endl;
cout<<" to 0, then call Print List before function ends)"<<endl;
cout<<"4. Quit"<<endl;
cout<<"---------------------------------------------------------"<<endl;
}
//Modification Functions
void List::set_value(const int value)
{
if (slot == 0) //If first run set array size
{
array = new int[array_size];
}
if (slot == array_size) //If array needs extended save data in temp array expand original array then copy back to original
{
cout<<"EXPAND ARRAY"<<endl;
temp_array = array;
array_size = array_size + 2;
array = new int[array_size];
array = temp_array;
}
array[slot] = value; //Set current array slot to value
slot = slot+1;
}
void List::print_list(void) const
{
int i = 0;
cout<<"---------------"<<endl;
while(i < slot)
{
cout<<array[i]<<endl;
i = i+1;
}
cout<<"---------------"<<endl;
}
void List::test_copy_constructor(void) const
{
int* test_array;
test_array = array;
int i = 0;
test_array = new int[array_size]; //Copy original array to test_Array
while(i < slot) //Set array to 0
{
test_array[i] = 0;
i = i+1;
}
i = 0;
cout<<"---------------"<<endl;
while(i < slot) //REMOVE THIS ONLY FOR TESTING PURPOSES
{
cout<<test_array[i]<<endl;
i = i+1;
}
i = 0;
cout<<"---------------"<<endl;
List::print_list(); //Print original array
}
void Set::set_value(const int value)
{
array = get_array(); //Use get functions to obtain copies of private data
temp_array = get_temp_array();
array_size = get_array_size();
temp_array_size = get_temp_array_size();
slot = get_slot();
char match;
match = Set::search_array(value);
if(match == 'y')
{
cout<<"Match"<<endl;
}
if(match == 'n')
{
if (slot == 0) //If first run set array size
{
array = new int[array_size];
}
if (slot == array_size) //If array needs extended save data in temp array expand original array then copy back to original
{
cout<<"EXPAND ARRAY"<<endl;
temp_array = array;
array_size = array_size + 2;
array = new int[array_size];
array = temp_array;
}
array[slot] = value; //Set current array slot to value
slot = slot+1;
set_array(array); //Use set values to update private data
set_temp_array(temp_array);
set_array_size(array_size);
set_temp_array_size(temp_array_size);
set_slot(slot);
}
}
char Set::search_array(int value)
{
array = get_array();
array_size = get_array_size();
slot = get_slot();
int array_value;
char match = 'n';
int i =0;
while(i < slot) //Searches array for a match if there is return y otherwise return n
{
if( array[i] == value)
{
match = 'y';
}
else
{
match = 'n';
}
i = i+1;
}
return match;
}
//Set Functions
void List::set_array(int* value)
{
array = value;
}
void List::set_array_size(int value)
{
array_size = value;
}
void List::set_temp_array(int* value)
{
temp_array = value;
}
void List::set_temp_array_size(int value)
{
temp_array_size = value;
}
void List::set_slot(int value)
{
slot = value;
}
//Get Functions
int* List::get_array(void) const
{
return array;
}
int* List::get_temp_array(void) const
{
return temp_array;
}
int List::get_array_size(void) const
{
return array_size;
}
int List::get_temp_array_size(void) const
{
return temp_array_size;
}
int List::get_slot(void) const
{
return slot;
}
set.h
#ifndef set_H_INCLUDED
#define set_H_INCLUDED
class List
{
public:
//Constructor
List();
//Print Functions
void header (void) const;
void menu (void) const;
//Modification Functions
void set_value (const int);
void print_list(void) const;
void test_copy_constructor(void) const;
//Set functions
void set_array( int*);
void set_temp_array(int*);
void set_array_size( int);
void set_temp_array_size(int);
void set_slot(const int);
//Get functions
int* get_array (void) const;
int* get_temp_array (void) const;
int get_array_size (void) const;
int get_temp_array_size (void) const;
int get_slot(void) const;
private:
int array_size;
int *array;
int *temp_array;
int temp_array_size;
int slot = 0;
};
class Set : public List
{
public:
//Modification Functions
void set_value (const int);
char search_array(const int);
private:
int array_size = 2;
int *array;
int *temp_array;
int temp_array_size = 2;
int slot = 0;
};
#endif
List::List()
{
int array_size;
int *array = new int[array_size];
// ...
}
What value is array_size supposed to have? How large an int array is supposed to be allocated?
It seems to me that this local variable declaration is superfluous; remove it, and use the member variable, instead. (You've initialised the member variable to 2 at its point of declaration, using a new C++11 feature which allows you to do so with a variable that is not static const.)
Don't forget to hand back that allocated memory when you're done with it. In general I would propose that you use std::vector for this.
This main program should ask the user to put in some numbers and store them into a dynamic array. The array should then be outputted its contents in a straight line, no end line commands, with a comma in between. I can't figure out how to start the program.
If you guys can help me find a way to do this, I would be eternally thankful!
Here is ListType.h:
#ifndef LISTTYPE_H_INCLUDED
#define LISTTYPE_H_INCLUDED
#include <iostream>
class ListType {
public:
ListType(size_t=10);
virtual ~ListType();
virtual bool insert(int)=0;
virtual bool erase();
virtual bool erase(int)=0;
virtual bool find(int) const=0;
size_t size() const;
bool empty() const;
bool full() const;
void output(std::ostream& out) const;
friend std::ostream& operator << (std::ostream&, const ListType&);
protected:
int *items;
size_t capacity;
size_t count;
};
#endif // LISTTYPE_H_INCLUDED
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 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 ListType.cpp:
#include "ListType.h"
ListType::ListType (size_t a) {
capacity = a;
count = 0;
items = new int [capacity];
}
ListType::~ListType() {
delete [] items;
}
bool ListType::erase() {
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);
}
void ListType::output(std::ostream& out) const {
for (int i = 0; i < count; i++) {
if (i > 0) {
out << ", ";
}
out << items[i];
}
}
std::ostream& operator << (std::ostream& out, const ListType& my_list) {
my_list.output(out);
return out;
}
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;
}
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];
while (i > 0 && items[i-1] > item){
newitems[i] = items[i];
}
delete [] items;
items = newitems;
}
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;
}
#include "ListType.h"
#include "UListType.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
UListType UL;
cout << "How many numbers do you want to put it?" << endl;
int n;
cin >> n;
cout << "All right, enter " << n << " numbers:" << endl;
int x;
for(int k=0; k<n; ++k)
{
cin >> x;
// do something with x
}
return(0);
}
You already have everything you need. Try the following
#include <iostream>
#include "OListType.h"
using namespace std;
int main()
{
OListType list;
int n;
do
{
cout << "Add a number [Y/n]?";
char a;
cin >> a;
if (a != 'n')
{
cin >> n;
list.insert(n);
}
else
{
list.output(cout);
break;
}
}while (1);
return 0;
}