my code is suppose to create a singly linked list using and array of nodes.
each Node has variable item which hold data and variable next which holds the index of the next node in the list. the last node has -1 in its next data field to simulate a nullptr. head holds the index of the first node in the list.
for some reason when i try to create new memory the program throws an instance of bad_alloc
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
#include "ArrayList.h"
#include <iostream>
using namespace std;
ArrayList::ArrayList(char ch){
array = new Node[Size];
(array[0]).item = ch;
(array[0]).next = 1;
free = 1;
head = 0;
}
bool ArrayList::cons(char ch) {
if (this->isFull()){
this->doubleArray();
}
(array[free]).item = ch;
(array[free]).next = head;
head = free;
free++;
// cout << free << endl;
return true;
}
bool ArrayList::isFull() const{
int current = head;
int count =0;
while( (array[current]).next != -1 ){
count++;
current = (array[current]).next;
}
return (count == Size) ? true : false;
}
bool ArrayList::doubleArray() {
int oldSize = Size;
Size *=2;
Node* newArray = new Node[Size]; // problem occurs here, i think
int count =0;
while(oldSize >= count ){
(newArray[count]).item = (array[count]).item;
(newArray[count]).next = (array[count]).next;
count++;
}
free = count +1;
delete [] array;
array = newArray;
cout <<"free: "<< free << endl;
return true; // come up with thiss
}
void ArrayList::print() const{
if (head == -1) return;
int current = head;
cout << "[ ";
while( (array[current]).next != -1){
cout << (array[current]).item <<" ";
current = (array[current]).next;
}
cout << (array[current]).item <<"]";
return;
}
///////////////////////////////////
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <iostream>
using namespace std;
class Node{
public:
char item;
int next;
Node(){
next = -1;
}
Node(char input){
this->item = input;
next = -1;
}
};
class ArrayList{
public:
ArrayList(char ch);
int length() const;
void print() const;
private:
bool doubleArray();
bool isFull() const;
Node* array;
int Size = 5;
int head = -1;
int free = 0;
};
#endif
////////////////////////////////////////
#include <iostream>
#include "ArrayList.h"
using namespace std;
int main(){
ArrayList list('1');
list.cons('2');
list.cons('3');
list.cons('4');
list.cons('5');
list.cons('6');
list.cons('7');
list.print();
//cout << list.length();
return 0;
}
Related
I am trying to get a linked-list class-based queue that holds objects of type "Student", but I've been trying for two days to get this thing to work. Now I am seeing errors of exceptions at the copy constructor of the "Student" class and the return of the dequeue function, and am at a complete loss since I don't even know what that means.
My main issue, from what I can tell, is when I try to assign the return of the dequeue to an object, there is an issue with the fact that I'm using the standard = operator and not a custom operator= for the class. Then again, I am relatively new to classes so I don't know if this is actually the issue.
This is the main code that uses all my files:
#include <iostream>
#include <fstream>
#include <string>
#include "Student.h"
#include "Queue.h"
int main(void)
{
char TempFName[15], TempSName[20];
long Tid_num;
int Tage;
float Tgpa;
Student Student1, StudentA;
queue q1;
int no, temp;
ifstream ip("input.txt");
// modify for your location
ip >> no; /* read in the number of Students */
for (temp = 0; temp < no; temp++)
{
/* read in the Student data in file format */
ip >> TempFName;
Student1.assignFName(TempFName);
ip >> TempSName;
Student1.assignSName(TempSName);
ip >> Tid_num;
Student1.assignId(Tid_num);
ip >> Tage;
Student1.assignAge(Tage);
ip >> Tgpa;
Student1.assignGpa(Tgpa);
q1.enqueue(Student1);
}
ip.close();
queue q2(q1);
q2.enqueue(StudentA);
q1.enqueue(StudentA);
cout << "details for queue 2 are as follows" << endl;
for (temp = 0; temp < no + 1; temp++)
{
Student1 = q2.dequeue();
Student1.print();
}
cout << "There are " << Student1.getNum() << " Student objects in existence";
return 0;
}
My files are:
Student.cpp:
#include <iostream> // need for cout, etc
#include "Student.h"
using namespace std;
Student::Student(const Student& s)
{
firstname = s.firstname;
surname = s.surname;
id_num = s.id_num;
age = s.age;
gpa = s.gpa;
count++;
}
Student::~Student() { count--; }
void Student::assignFName(string tempFName)
{
firstname = tempFName;
}
void Student::assignSName(string tempSName) { surname = tempSName; }
void Student::assignId(long Tid_num) { id_num = Tid_num; }
void Student::assignAge(int Tage) { age = Tage; }
void Student::assignGpa(float Tgpa) { gpa = Tgpa; }
string Student::getSName() { return surname; }
long Student::getId_num() { return id_num; }
int Student::getAge() { return age; }
float Student::getGpa() { return gpa; }
int Student::getNum() { return count; }
void Student::print() const
{
cout << firstname << " " << surname << " " << id_num << " " << age << " ";
cout << gpa << endl; // could do on same line, but do on next line just so can see that can be multiple lines, etc
}
int Student::count = 0;
Student.h:
#pragma once
//Module.h
#ifndef STD_H
#define STD_H
#include <string>
using namespace std;
class Student
{
public:
// just include one constructor definition here to show how it is written if do inline
Student(string fn = "nofirstname", string sn = "nosurname", long i = 0000, int a = 0, float s = 0)
:firstname(fn), surname(sn), id_num(i), age(a), gpa(s) {
count++;
}
Student(const Student& s);
~Student();
void assignFName(string tempFName);
void assignSName(string tempSName);
void assignId(long Tid_num);
void assignAge(int Tage);
void assignGpa(float Tgpa);
string getFName() { return firstname; } // just include one method here to show how it is written if do inline
string getSName();
long getId_num();
int getAge();
float getGpa();
void print() const;
static int getNum();
private:
string firstname, surname;
long id_num;
int age;
float gpa;
static int count;
};
#endif
queue.cpp:
#include "Queue.h"
#include "Student.h"
#include <iostream>
#include <stdlib.h>
void queue::enqueue(Student value) {
QueueNode* temp = new QueueNode(value); //allocating memory for the newly created node, with a value passed into it
if (tail == NULL) { //If there is no tail (i.e. only 1 block in the queue)...
head = tail = temp; //The tail and head are now the one block
return; //
} //
tail->next = temp; //The next address of the tail is made to equal the temporary node
tail = temp; //The tail becomes the temporary node
delete temp;
}
Student queue::dequeue() {
Student a;
if (head == tail) {//if only one node is there
head = tail = NULL;
} else {
head = head->next;
}
if (head == NULL) {
exit(1);
}
a = head->value;
return a;
//Student a;
//QueueNode* temp = head; //store the current head node of the queue
//delete (temp);
//if (head != NULL) {
// head = head->next;
//
//} else {
// tail = NULL;
// //return a;
//}
//a = head->value;
//return a;
}
void queue::printQueue() {
int count = 1; //initiazling counter variable as 1 so that the counter does not start at 0
while (head != NULL) //while the are still blocks in the queue
{
//cout << "\n\tBlock number " << count << " pushed: " << ; //print the block that was just inserted and what position it is at
head->value.print();
head = head->next; //equate the node to the next address
count++; //increment the counter
}
}
queue::~queue() {
head = tail = NULL;
}
queue::queue(const queue& q) {
QueueNode* hold = q.head;
QueueNode* temp, * oldtemp;
if (hold == q.tail)
{
temp = new QueueNode;
head = temp;
tail = temp;
}
else
{
temp = new QueueNode;
head = temp;
while (hold != q.tail)
{
// get the value at the node looking at on queue 'r' list
temp->value = hold->value;
// move to the next entry on 'r' list
hold = hold->next;
oldtemp = temp;
temp = new QueueNode;
oldtemp->next = temp;
}
tail = temp;
}
}
queue::queue() {
head = tail = NULL;
}
//queue::sizeOfQueue() { //function to return the number of nodes in the queue
// //takes in the pointer to the queue so that the function knows which queu to get the size of
// int size = 0; //intialize size integer to be returned
// while (node != NULL) { //for as long as a NULL node is not reached
// node = node->next; //equate the node to the next address
// size++; //increment the size integer
// } //eventually the node will reach the end of the queue where the next address is NULL (because there are no other nodes)
// return size; //return the integer for the size
//}
queue.h:
#pragma once
#include "Student.h"
#include "Node.h"
class queue {
public:
queue();
queue(const queue& q);
~queue();
void enqueue(Student value);
Student dequeue();
void printQueue();
private:
QueueNode* head;
QueueNode* tail;
};
Node.cpp:
#include "Queue.h"
#include "Node.h"
#include "Student.h"
#include <iostream>
QueueNode::QueueNode() {
value = Student();
next = NULL;
}
QueueNode::QueueNode(Student val) {
value = val;
next = NULL;
}
QueueNode::~QueueNode() {
value.~Student();
next = NULL;
}
Node.h:
#pragma once
#include "Student.h"
class QueueNode {
friend void enqueue(Student value);
friend void dequeue();
friend void printQueue();
public:
QueueNode* next; //PUBLIC VARIABLE
Student value;
QueueNode();
QueueNode(Student val);
~QueueNode();
private:
};
The input file that gets the details for the "Student" objects that go in the queue:
3
joe bloggs 40001 24 2.1
mary doe 40002 19 3.9
john boyd 40003 18 1
I have a HashTable class. The purpose of this is to practice how to produce Hash Table. My current issue right now is the destructor. I should be seeing on the console, this:
But instead i see this:
I've ran gdb ./app which gives me this:
#include <iostream>
#include "HashTable.h"
using namespace std;
int main(){
HashTable table;
table.initTable();
table.addNode("Software");
table.addNode("Engineering");
table.addNode("Art");
table.addNode("Programming");
table.addNode("Miscellanous");
table.displayByIndex();
return 0;
}
HashTable Header:
#ifndef _HASHTABLE_H_
#define _HASHTABLE_H_
#include <iostream>
#include "Hash.h"
class HashTable{
private:
static const int TABLESIZE = 5;
Hash* head;
public:
HashTable();
~HashTable();
void initTable();
int hashKey(char*);
int quadProbing(int,int);
int hashKeyWithProbing(char*);
bool isEmpty();
void addNode(char*);
void displayByIndex();
void searchByKey(char*);
};#endif
Here it my Hash Table CPP, i included the Constructor/Destructor and init functions. The other functions arent included since i dont utilize the 'new' keyword. If its needed i will include it [hope to make this thread small]
#include "HashTable.h"
#include <cstring>
HashTable::HashTable(){
head = new Hash[TABLESIZE];
}
HashTable::~HashTable(){
Hash* destList = NULL;
for(int i = 0; i< TABLESIZE; i++){
destList = &head[i];
while(destList != NULL){
head = head->getNext();
delete destList;
destList = head;
}
}
head = NULL;
delete [] head;
}
void HashTable::initTable(){
for(int i = 0; i < TABLESIZE; i++){
Hash *traverseHeadArray = &head[i];
traverseHeadArray->setKey("EMPTY");
traverseHeadArray->setNext(NULL);
traverseHeadArray = NULL;
}
}
int HashTable::hashKey(char *tempKey){
//Find the asc value for the string
//add them together
//modules by the total table size
//then return the index (remainder using modules)
//Index is were that key will be stored
int index = 0;
for(int i = 0; i < strlen(tempKey); i++){
index += tempKey[i];
}
return index % TABLESIZE;
}//DONE
int HashTable::quadProbing(int index, int counter){
return (index + counter*counter) % TABLESIZE;
}//DONE
int HashTable::hashKeyWithProbing(char* key){
int index = hashKey(key);
int count = 1;
while(head[index].getKey() != key && head[index].getKey() != "EMPTY"){
index = quadProbing(index, count);
count++;
}
return index;
}//DONE
void HashTable::addNode(char* tempValue){
Hash* newNode = new Hash;
newNode->setKey(tempValue);
newNode->setNext(NULL);
int index = hashKey(tempValue);
int counter = 1;
while(head[index].getKey() != tempValue && head[index].getKey() !="EMPTY")
{
index = quadProbing(index, counter);
counter++;
}
Hash* traverse = &head[index];
if(isEmpty() || traverse->getKey() == "EMPTY"){
traverse->setKey(newNode->getKey());
traverse->setNext(newNode->getNext());
}else{
while(traverse->getNext() != NULL)
traverse = traverse->getNext();
traverse->setNext(newNode);
}
traverse = NULL;
delete newNode;
}
void HashTable::displayByIndex(){
for(int i = 0; i < TABLESIZE; i++){
Hash *traverse = &head[i];
std::cout << "----------------------------------------" << std::endl;
std::cout << "INDEX: " << i << std::endl;
while(traverse != NULL){
std::cout << "Key: " << traverse->getKey() << std::endl;
traverse = traverse->getNext();
}
std::cout << "----------------------------------------" << std::endl;
traverse = NULL;
}
}
bool HashTable::isEmpty(){
return (head == NULL);
}
void HashTable::searchByKey(char* key){
int index = hashKeyWithProbing(key);
if(isEmpty())
std::cout << "Empty Bucket\n";
else{
Hash* traverse = &head[index];
while(traverse != NULL && traverse->getKey() != "EMPTY"){
std::cout << "TOPIC KEY: " << traverse->getKey() << std::endl;
traverse = traverse->getNext();
}
traverse = NULL;
}
}
Here is my Hash Class header and CPP files:
#ifndef _HASH_H_
#define _HASH_H_
class Hash{
private:
char* key;
Hash* next;
public:
Hash();
~Hash();
void setKey(char*);
void setNext(Hash* const);
char* getKey();
Hash* getNext();
};#endif
#include "Hash.h"
#include <iostream>
Hash::Hash(){
key = NULL;
next = NULL;
}
Hash::~Hash(){
// TODO Destructor
}
void Hash::setKey(char* tempKey){
this->key = tempKey;
}
void Hash::setNext(Hash* const tempNext){
this->next = tempNext;
}
char* Hash::getKey(){
return key;
}
Hash* Hash::getNext(){
return next;
}
In your code, you allocating only the getNext() nodes,
so you should delete only them, (you tried to delete &head[i] which wasn't allocated at all).
There is still an exception for double freeing some node, you should debug and follow the stack for figuring it out.
HashTable::~HashTable(){
for(int i = 0; i< TABLE_SIZE; i++){
Hash* node = head[i].getNext();
while(node != nullptr){
Hash* temp = nullptr;
if (node -> getNext()) {
temp = node->getNext();
}
delete node;
node= temp;
}
}
delete[] head;
}
Output:
----------------------------------------
INDEX: 0
Key: Art
----------------------------------------
----------------------------------------
INDEX: 1
Key: Engineering
----------------------------------------
----------------------------------------
INDEX: 2
Key: Miscellanous
----------------------------------------
----------------------------------------
INDEX: 3
Key: Software
----------------------------------------
----------------------------------------
INDEX: 4
Key: Programming
----------------------------------------
double free or corruption (fasttop)
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
I have tried my best to look for an answer that addresses my specific question but unfortunately, I wasn't able to find one that satisfied my needs.
I am writing an assembler in c++ for a language that I made up. Writing the assembler involves two classes that have been causing problems really tough to debug. My debugging techniques have devolved to adding and removing output stream commands like
std::cout << "TEST";
which end up either breaking or fixing the program. The IDE I am using is Xcode.
The two classes that I am working on are a LinkedList class and a SymbolTable class, which I am using as a hash table for symbol resolution.
LinkedList.h
#include <iostream>
using namespace std;
struct Node{
string data;
int address;
Node* next = nullptr;
};
class LinkedList{
private:
Node* main_ptr;
int length;
public:
LinkedList();
void insertNode(string, int);
void deleteNode(string);
void displayList();
bool contains(string, int* = nullptr);
int getLength();
~LinkedList();
};
LinkedList.cpp
#include "LinkedList.h"
LinkedList::LinkedList(){
main_ptr = nullptr;
length = 0;
}
void LinkedList::insertNode(string data, int address){
Node* newNode = new Node;
newNode->data = data;
newNode->address = address;
if (!main_ptr){
main_ptr = newNode;
} else {
newNode->next = main_ptr;
main_ptr = newNode;
}
length++;
}
void LinkedList::deleteNode(string data){
if (main_ptr){
int current_length = length;
if (main_ptr->data == data){
main_ptr = main_ptr->next;
return;
}
Node* q = main_ptr;
Node* p = q;
q = q->next;
while (q){
if (q->data == data){
p->next = q->next;
length--;
return;
}
p = q;
q = q->next;
}
if (current_length == length) cout << "Node was not found" << endl;
} else {
cout << "List is empty, cannot delete node!" << endl;
}
}
void LinkedList::displayList(){
if (!main_ptr){
cout << "List is empty!\n";
} else {
Node* temp = main_ptr;
while (temp){
cout << temp->data;
temp = temp->next;
}
cout << endl;
}
}
bool LinkedList::contains(string data, int* address){
if (main_ptr == nullptr) return false;
else {
Node* temp = main_ptr;
while(temp != nullptr){
if (temp->data == data) {
address = &(temp->address);
return true;
}
temp = temp->next;
}
return false;
}
}
int LinkedList::getLength(){
return length;
}
LinkedList::~LinkedList(){
if (main_ptr){
Node* q = main_ptr;
Node* p = q;
while (q){
q = q->next;
delete p;
p = q;
}
}
}
SymbolTable.h
#include "LinkedList.h"
#include <iostream>
class SymbolTable{
private:
LinkedList table[701];
public:
SymbolTable();
void addEntry(string, int);
void printTable();
bool contains(string, int*);
int convertName(string);
};
SymbolTable.cpp
#include "SymbolTable.h"
SymbolTable::SymbolTable(){
}
void SymbolTable::addEntry(string name, int memory){
int address = convertName(name);
table[address].insertNode(name, memory);
}
void SymbolTable::printTable(){
for (int i = 0; i < 701; i++)
table[i].displayList();
}
bool SymbolTable::contains(string name, int* memory){
return table[convertName(name)].contains(name, memory);
}
int SymbolTable::convertName(string name){
int aggregate = 1;
const char* c_name = name.c_str();
for (int i = 0; i < name.length(); i++){
aggregate *= (int)c_name[i];
}
return aggregate%701;
}
Now comes my actual question. The following is the main function:
#include "Parser.h"
#include "SymbolTable.h"
using namespace std;
int main(int argc, const char * argv[]) {
ifstream inputFile;
ofstream outputFile;
inputFile.open("/Users/Azaldin/Desktop/nand2tetris/projects/06/max/Max.asm");
outputFile.open("/Users/Azaldin/Desktop/nand2tetris/projects/06/max/Max.hack");
Parser a(inputFile);
SymbolTable s;
int commandType = -1;
string command;
int a_position = 16;
int currentLine = 0;
while (a.hasMoreCommands()){
a.advance();
commandType = a.commandType();
command = a.symbol();
if (commandType == 0){
if (!s.contains(command, nullptr)){
s.addEntry(command, a_position);
a_position++;
}
}
if (commandType == 2){
//cout << command << endl;
if (!s.contains(command, nullptr)){
s.addEntry(command, currentLine);
//cout << command << endl;
}
}
currentLine++;
}
string x; //<<<<<<<<<< ADDING THIS LINE BREAKS THE PROGRAM
cout << "Hi";
inputFile.close();
outputFile.close();
return 0;
}
After adding the line pointed to above in the main function, the program breaks.
Upon debugging, the following problem arises from the main thread:
Thread 1:EXC_BAD_ACCESS (code = 1, address=0x25fbfef80)
The chain of commands that leads to this problem:
if (!s.contains(command, nullptr)){ from the main function
return table[convertName(name)].contains(name, memory); from the SymbolTable.cpp "contains" function
if (temp->data == data) { from LinkedList.cpp "contains" function
The rest of the chain command leads to the string class == operator, which then leads to the .size() function on the left-hand side.
Thank You!
The following comment by PaulMcKenzie helped solve the problem:
Also, aggregate *= (int)c_name[i]; -- there is no guarantee that this
will be a positive number, since a character may be signed, thus
giving you values of -1 and below. Thus your return of return
aggregate%701; isn't going to return what you expected (a number >=
0).
It turns out that one of the arguments passed into the convertName function in the SymbolTable class have caused the program to corrupt the memory. I added an if statement to solve the problem.
I'm trying to make a stack of hash tables with the push and pop functions. I have the push and pop down, but is there a way to modify the stack to put H1 and H2 into Stack One? Currently, my stack holds ints for testing purposes.
Below are all headers and source files. I'd really like a solution for this issue. Thanks.
Stack.h
#ifndef STACK_H
#define STACK_H
#include <string>
using namespace std;
class Stack
{
private:
struct item
{
int value;
item* prev;
};
item* stackPtr;
public:
void Push(int value);
void Pop();
void ReadItem(item* r);
void Print();
Stack(); //called when stack is created
~Stack();//called when stacked item is ended
};
#endif /* STACK_H */
Stack.cpp
#include <iostream>
#include <cstdlib>
#include "Stack.h"
using namespace std;
Stack::Stack()
{
stackPtr = NULL;
}
Stack::~Stack()
{
item* p1; //pointer 1
item* p2; //pointer 2
p1 = stackPtr;
while(p1 != NULL)
{
p2 = p1;
p1 = p1->prev;
p2->prev = NULL;
delete p2;
}
}
void Stack::Push(int value)
{
item* n = new item;
n->value = value;
if(stackPtr == NULL)
{
stackPtr = n;
stackPtr->prev = NULL;
}
else
{
n->prev = stackPtr;
stackPtr = n;
}
}
void Stack::ReadItem(item* r)
{
cout << "value: " << r->value << endl;
cout << "------------------\n";
}
void Stack::Pop()
{
if(stackPtr == NULL)
{
cout << "The stack is empty\n";
}
else
{
item* p = stackPtr;
ReadItem(p);
stackPtr = stackPtr->prev;
p->prev = NULL;
delete p;
}
}
void Stack::Print()
{
item* p = stackPtr;
while(p != NULL)
{
ReadItem(p);
p = p->prev;
}
}
Hashtable.h
#include <cstdlib>
#include <iostream>
#include <string>
#ifndef HASHTABLE_H
#define HASHTABLE_H
class HashTable
{
private:
static const int tableSize = 10;
//everything in the braces are what makes the item
struct obj
{
int name;
obj* next;
};
obj* HASHTBL[tableSize];
public:
HashTable();
//Hash is the function represents where in the hash table
//we will store the key
//take a string stored in variable
int Hash( int key);
void AddObj(int name);
int ItemsinBucket(int index);
void PrintTable();
};
#endif /* HASHTABLE_H */
Hashtable.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "HashTable.h"
using namespace std;
//Takes from the HashTable class in HashTable.h
HashTable::HashTable()
{
for(int x = 0; x < tableSize; x++)
{
HASHTBL[x] = new obj;
HASHTBL[x]->name = NULL;
HASHTBL[x]->next = NULL;
}
}
void HashTable::AddObj( int name)
{
int index = Hash(name);
if(HASHTBL[index]->name == NULL)
{
HASHTBL[index]->name = name;
}
else
{
obj* Ptr = HASHTBL[index];
obj* n = new obj;
n->name = name;
n->next = NULL;
while(Ptr->next !=NULL)
{
Ptr = Ptr->next;
}
Ptr->next = n;
}
}
int HashTable::ItemsinBucket(int index)
{
int count = 0;
if (HASHTBL[index]->name == NULL)
{
return count;
}
else
{
count++;
obj* Ptr = HASHTBL[index];
while(Ptr->next != NULL)
{
count++;
Ptr = Ptr->next;
}
}
return count;
}
void HashTable::PrintTable()
{
int number;
for(int x = 0; x< tableSize; x++)
{
number = ItemsinBucket(x);
cout << "------------------------\n";
cout << "index = " << x << endl;
cout << HASHTBL[x]->name << endl;
cout << "The num of items in index = "<< number << endl;
cout << "------------------------\n";
}
}
int HashTable::Hash(int key)
{
//defining HashTable function:
int HashTable = 0;
int index;
//will return integer value...or length of string you pass in
for(int x = 0; x < key-1; x++)
{
HashTable = HashTable + x;
}
//so the hash table will take a number and mod it to return the remainder
//the remainder is the index
index = HashTable % tableSize;
return index;
}
main.cpp
#include <iostream>
#include <cstdlib>
#include "Stack.h"
#include "HashTable.h"
using namespace std;
int main(int argc, char** argv)
{
Stack One;
One.Push(3);
One.Push(0);
One.Push(4);
One.Push(5);
HashTable H1;
H1.AddObj(4);
H1.AddObj(23);
H1.AddObj(200);
H1.AddObj(10);
H1.AddObj(15);
H1.AddObj(42);
H1.AddObj(33);
H1.AddObj(44);
H1.AddObj(55);
H1.AddObj(5);
H1.AddObj(9);
H1.AddObj(90);
HashTable H2;
H2.AddObj(10);
H2.AddObj(90);
H2.AddObj(99);
H2.AddObj(34);
H2.AddObj(88);
H2.AddObj(14);
H2.AddObj(87);
H2.AddObj(18);
H2.AddObj(54);
H2.AddObj(56);
H2.AddObj(6);
H2.AddObj(2);
One.Print();
cout << "\n\n\n";
H1.PrintTable();
/*
cout << "1. Push Stack Element" << endl;
cout << "2. Pop Stack Element" << endl;
cout << "3. Search Hash Table" << endl;
*/
return 0;
}
I have tried looking at videos and older posts but it is still very difficult to understand the concept of copy constructors. Would someone clear it up for me? My class did not really cover this part 100% my professor focused mainly on constructors and destructors.
Main CPP
#include <iostream>
#include "Header.h"
using namespace std;
int main()
{
node access;
access.getData();
access.outData();
system("pause");
return 0;
}
Header File
#include <iostream>
using namespace std;
class node
{
public:
node(); // Had to create my own default constructor because of my copy constructor.
node(const node &n); // This is a copy constructor.
~node();
void getData();
void outData();
private:
int num;
int lCount = 0; // Counts the number of nodes, increments after each user input.
int *ptr; // Where the linked list will be copied into
node *next;
node *first;
node *temp;
node *point;
};
node::node()
{
num = 0;
}
node::node(const node &n)
{
temp = first;
ptr = new node;
for (int i = 0; i < lCount; i++)
{
ptr[i] = temp->num;
temp = temp->next;
}
}
node::~node() // Deletes the linked list.
{
while (first != NULL)
{
node *delP = first; // Creates a pointer delP pointing to the first node.
first = first->next; // "Removes first node from the list and declares new first.
delete delP; // Deletes the node that was just removed.
}
cout << "List deleted" << endl;
}
void node::getData() // Simple function that creates a linked list with user input.
{
int input = 0;
point = new node;
first = point;
temp = point;
while (input != -1)
{
cout << "Enter any integer, -1 to end." << endl;
cin >> input;
if (input == -1)
{
point->next = NULL;
break;
}
else
{
lCount++;
point->num = input;
temp = new node;
point->next = temp;
point = temp;
}
}
}
void node::outData()
{
temp = first;
cout << "Original" << endl;
while (temp->next != NULL)
{
cout << temp->num << endl;
temp = temp->next;
}
cout << "Copied" << endl;
for (int i = 0; i < lCount; i++)
{
cout << ptr[i] << endl;
}
}
This little snippet is what I am having trouble with in particular:
node::node(const node &n)
{
temp = first;
ptr = new node;
for (int i = 0; i < lCount; i++)
{
ptr[i] = temp->num;
temp = temp->next;
}
}
I figured it out! I was tinkering with a much simpler copy constructor. I was having trouble understanding syntax, everything was very complicated and it was overwhelming to look at.
#include <iostream>
using namespace std;
class node
{
public:
node(int x); // Normal Construtor
node(const node &cpy); // Copy Constructor
void change(); // Changes data value
void outData();
private:
int data;
};
int main()
{
node var1(123);
var1.outData();
node var2 = var1;
var2.outData();
var2.change();
var1.outData();
var2.outData();
system("pause");
return 0;
}
node::node(int x)
{
data = x;
}
node::node(const node &cpy)
{
data = cpy.data;
}
void node::outData()
{
cout << data << endl;
}
void node::change()
{
int userIn;
cin >> userIn;
data = userIn;
}
Output:
123
123
(input: 4444)
Output:
123
4444