Not able to access functions from object - c++

I am working on a project which I have to include a header file to my main.cpp. The header file is a heap which is using a template file. For reasons that escape me the insert and remove functions cannot be "seen" in the main file. I am getting an error message: C:/Users/Tito/Documents/C++proj/cs3304/Homework2_2/Homework10/main.cpp:58:17: error: request for member 'remove' in 'enter1', which is of non-class type 'priority_queue_heap()'. Can someone please tell me where I am going wrong? I will really appreciate it.
Thanks
Here are the lines of code:
Main.cpp:
/**
* Insert a few elements into a heap and the remove them
* one by one and see if we get them in the right.
*/
#include "priority_queue_heap.h"
#include "heap.h"
#include <iostream>
#include <ctime>
using namespace std;
int test1() {
heap<int> hp;
hp.insert(1);
hp.insert(2);
hp.insert(3);
hp.insert(4);
hp.insert(5);
hp.check_heap();
int x = hp.remove();
cout << "removed " << x << endl;
x = hp.remove();
cout << "removed " << x << endl;
x = hp.remove();
cout << "removed " << x << endl;
x = hp.remove();
cout << "removed " << x << endl;
x = hp.remove();
cout << "removed " << x << endl;
cout << "empty? " << hp.is_empty() << endl;
}
void test2() {
srand(time(NULL));
heap<int> hp;
for(int i = 0; i < 30; i++ ) {
hp.insert(rand());
}
while(!hp.is_empty()) {
int x = hp.remove();
cout << x << endl;
}
}
int main() {
/*test1();
test2();*/
priority_queue_heap<int> enter1();
enter1.insert(135);
enter1.insert(909);
enter1.insert(203);
cout<<endl;
cout<< "values to be removed" << endl;
cout << enter1.remove() << endl;
}
heap.h:
#ifndef HEAP_H
#define HEAP_H
/**
* This class implements a heap as described in the text.
* We will treat it as a priority queue.
*/
template <class T>
class heap {
public:
static const int CAPACITY = 10;
heap() {
size = 0;
}
bool is_empty() const { return size == 0;}
bool is_full() const { return size == CAPACITY; }
/**
* Remove the largest value from this heap and return it.
*
* Precondition: heap is not empty.
*/
T remove();
/**
* Inserts the 'value' into the heap.
*
* Precondition: heap is not full
*/
void insert(const T& value);
/**
* Check if the heap is valid.
* Prints out each parent and its children (for all nodes with children)
* Stops when a parent is less than one or both of its children
* Prints 'check' for each parent that is greater than or equal to its
children
*/
bool check_heap();
private:
T data[CAPACITY];
int size;
};
#include "heap.template"
#endif // HEAP_H
heap.template:
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <iomanip>
/*
* parent index is p, children are at indices 2*p+1 and 2*p+2
* You must check that those are in range
*
* child index is c, parent index is (c-1)/2 (integer division)
*/
/**
* Inserts the 'value' into the heap.
*
* Precondition: heap is not full
*/
template <class T>
void heap<T>::insert(const T& value) {
assert(!is_full());
//std::cout << size << std::endl;
// add the value to a new node in proper position
data[size] = value;
size++;
// move the value up the tree as needed
int child = size-1; // index of the new 'node'
int parent = (child-1)/2; // index of the parent
while((child > 0) && (data[parent] < data[child])) {
// swap parent and child values
T tmp = data[parent];
data[parent] = data[child];
data[child] = tmp;
// update parent and child
child = parent; // this is where new value is!
parent = (child-1)/2;
}
// it's a heap!
}
/**
* Remove the largest value from this heap and return it.
*
* Precondition: heap is not empty.
*/
template <class T>
T heap<T>::remove() {
assert(!is_empty());
// grab first element, save it for return later
T save = data[0];
// copy last value in list to the beginning
// decrement size
data[0] = data[size-1];
size--;
// size--;
// data[0] = data[size];
// sift the new first element down until it finds its place
int parent = 0;
int left_child = 2*parent+1;
int right_child = 2*parent+2;
bool still_working = true;
while(still_working && left_child < size) { // while the parent has at
least one child
if(right_child >= size) {
// only the left child to worry about
if(data[parent] < data[left_child]) {
// out of order, so swap them
T t = data[parent];
data[parent] = data[left_child];
data[left_child] = t;
parent = left_child;
still_working = false; // we must be done!
} else {
still_working = false;
}
} else {
// two children
if(data[left_child] > data[right_child]) {
//left child larger
if(data[parent] < data[left_child]) {
// out of order, so swap them
T t = data[parent];
data[parent] = data[left_child];
data[left_child] = t;
parent = left_child;
} else {
still_working = false;
}
} else {
// right child larger
if(data[parent] < data[right_child]) {
// out of order, so swap them
T t = data[parent];
data[parent] = data[right_child];
data[right_child] = t;
parent = right_child;
} else {
still_working = false;
}
}
left_child = 2*parent + 1;
right_child = 2*parent + 2;
}
}
return save;
}
/**
* Check if the heap is valid.
* Prints out each parent and its children (for all nodes with children)
* Stops when a parent is less than one or both of its children
* Prints 'check' for each parent that is greater than or equal to its
children
*/
template <class T>
bool heap<T>::check_heap() {
for(int p = 0; p < size; p++ ) {
int cl = 2*p+1;
int cr = 2*p+2;
std::cout << std::setw(5) << p << std::setw(10) << data[p];
if(cl < size) { // p has a left child?
std::cout << std::setw(10) << data[cl];
if(data[p] < data[cl]) {
std:exit(1);
}
}
if(cr < size) { // p has a right child?
std::cout << std::setw(10) << data[cr];
if(data[p] < data[cr])
std::exit(1);
}
std::cout << std::endl;
}
return true;
}
priority_queue_simple.template:
#include <cassert>
/**
* Remove the largest value from this priority queue and return it.
*
* Precondition: priority queue is not empty.
*/
template <class T>
T priority_queue_simple<T>::remove() {
assert(size > 0);
int imax = 0;
for(int i = 1; i < size; i++ ) {
if(data[i] > data[imax])
imax = i;
}
T tmp = data[imax];
data[imax] = data[size-1];
size--;
return tmp;
}
/**
* Inserts the 'value' into the priority queue.
*
* Precondition: priority queue is not full
*/
template <class T>
void priority_queue_simple<T>::insert(const T& value) {
assert(size < CAPACITY);
size++;
data[size-1] = value;
}
priority_queue_heap.h:
#ifndef PRIORITY_QUEUE_HEAP_H
#define PRIORITY_QUEUE_HEAP_H
//#include "heap.h"
template <class T>
class priority_queue_heap {
priority_queue_heap();
bool is_empty() const;
bool is_full() const;
/**
* Remove the largest value from this priority queue and return it.
*
* Precondition: priority queue is not empty.
*/
T remove();
/**
* Inserts the 'value' into the priority queue.
*
* Precondition: priority queue is not full
*/
void insert(const T& value);
private:
heap<T> pri_que;
};
#include "priority_queue_heap.template"
#endif // PRIORITY_QUEUE_HEAP_H
template <class T>
T priority_queue_heap<T>::remove()
{
return pri_que.remove();
}
priority_queue_heap.template:
template <class T>
T priority_queue_heap<T>::remove()
{
return pri_que.remove();
}
template <class T>
void priority_queue_heap<T>::insert(const T& value)
{
pri_que.insert(value);
}
priority_queue_simple.h:
#ifndef PRIORITY_QUEUE_SIMPLE_H
#define PRIORITY_QUEUE_SIMPLE_H
/**
* This class implements a priority queue using a very simple strategy:
* Store the values in an array.
* Add new values at the end.
* When asked to remove a value, search for the largest (linear search)
*
*/
template <class T>
class priority_queue_simple {
public:
static const int CAPACITY = 30;
priority_queue_simple() {
size = 0;
}
bool is_empty() const {
return size == 0;
}
bool is_full() const {
return size == CAPACITY;
}
/**
* Remove the largest value from this priority queue and return it.
*
* Precondition: priority queue is not empty.
*/
T remove();
/**
* Inserts the 'value' into the priority queue.
*
* Precondition: priority queue is not full
*/
void insert(const T& value);
private:
T data[CAPACITY];
int size;
};
#include "priority_queue_simple.template"
#endif // PRIORITY_QUEUE_SIMPLE_H

You should remove the "()" characters after enter1 at line 51 of main.cpp ...
Otherwise c++ sees that as a function, it does not call the constructor.

You have a subtle error in your heap declaration (main.cpp:57):
priority_queue_heap<int> enter1();
Here you are actually declaring a prototype for the enter1 function that takes no argument and returns a priority_queue_heap<int>. Just remove the parentheses to actually declare a variable:
priority_queue_heap<int> enter1;

priority_queue_heap<int> enter1();
Is interpreted by the compiler as a function named enter1 that returns a priority_queue_heap<int> and takes no parameters. When you use
cout << enter1.remove() << endl;
You are trying to call a member function on a name that the compiler interpreted as a function so that is why it tells you it is of non class type. Remove the () from enter1 so you have
priority_queue_heap<int> enter1;
and now enter1 will be an object of type priority_queue_heap<int>

Related

C++ Copy Constructor Results in Memory Error

so the code, basically an AList with multiple functions, I have below currently runs fine and my passes all assertions and test cases that are assigned to my assignment, however, I lose .5 points because of a memory error. I believe the error lies somewhere in my copy constructor, but I am currently struggling to know where is the issue.
This is how my code looks along with my copy constructor.
#ifndef __ALIST_H__
#define __ALIST_H__
// size should not be negative
typedef unsigned long size_t;
#define RFACTOR 2 // use factor 2
namespace ds {
template <typename ItemType> class TestDriver; // for autograding; please ignore
/** Array-based list. */
template <typename ItemType> class AList {
friend class TestDriver<ItemType>; // for autograding; please ignore
private:
/** The underlying array. */
ItemType *items;
/** Stores the current size of the list. */
size_t count;
/** Max number of items allowed. */
size_t maxCnt;
/** Resize the underlying array to the target capacity. */
void resize(size_t capacity) {
maxCnt = capacity;
ItemType *a = new ItemType[maxCnt];
for (size_t i = 0; i < count; i++) {
a[i] = items[i];
}
delete[] items;
items = a;
}
public:
/**
* Construct a new AList object.
*
* #param initSize initial size of the underlying array; default 100
*/
AList(size_t initSize = 100) {
count = 0;
maxCnt = initSize;
items = new ItemType[maxCnt];
}
/** Destroy the AList object. */
~AList() { delete[] items; }
/** Return the number of elements in list. */
size_t size() const { return count; }
/** Return the i-th item in list .*/
ItemType &get(int i) const { return items[i]; }
/** Append `x` to the end of list. */
void addLast(ItemType x) {
if (count == maxCnt) {
resize(count * RFACTOR);
}
items[count] = x;
count += 1;
}
/** Return the last item in list. */
ItemType &getLast() const { return items[count - 1]; }
/** Delete and return the last item. */
ItemType removeLast() {
ItemType returnItem = getLast();
count -= 1;
return returnItem;
}
AList(const AList<ItemType> &other);
void addFirst(ItemType x);
ItemType &getFirst() const;
ItemType removeFirst();
};
/** Copy constructor. */
template <typename ItemType>
AList<ItemType>::AList(const AList<ItemType> &other) {
// TODO: create a list that is identical to `other`
count = other.count;
maxCnt = other.maxCnt;
ItemType arr[maxCnt];
items = new ItemType[maxCnt];
for(size_t i = 0; i < count; i++)
{
items[i] = arr[i];
}
delete [] items;
items = other.items;
}
/** Insert x at the front of list. */
template <typename ItemType> void AList<ItemType>::addFirst(ItemType x) {
// TODO:
if(count == maxCnt)
{
resize(count * RFACTOR);
}
for(size_t i = count; i > 0; i--)
{
items[i] = items[i - 1];
}
items[0] = x;
count = count + 1;
}
/** Return the first element in list. */
template <typename ItemType> ItemType &AList<ItemType>::getFirst() const {
// TODO:
return items[0];
}
/** Delete and return the first element in list. */
template <typename ItemType> ItemType AList<ItemType>::removeFirst() {
// TODO:
ItemType temp = items[0];
for(size_t i = 0; i < count - 1; i++)
{
items[i] = items[i + 1];
}
count = count - 1;
return temp;
}
} // namespace ds
#endif // __ALIST_H__
When I run my code, this is what the memory error states:
Output: 'original list: [1]; copy & getFirst: 1; resulting list: [1]'
217Expected: 'original list: [1]; copy & getFirst: 1; resulting list: [1]'
218Error(s):
219==190== Invalid free() / delete / delete[] / realloc()
220==190== at 0x483D74F: operator delete[](void*) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
221==190== by 0x10979A: ds::AList<int>::~AList() (AList.h:51)
222==190== by 0x10962E: main (test_driver.cpp:55)
223==190== Address 0x4da3cc0 is 0 bytes inside a block of size 4 free'd
224==190== at 0x483D74F: operator delete[](void*) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
225==190== by 0x10979A: ds::AList<int>::~AList() (AList.h:51)
226==190== by 0x109608: main (test_driver.cpp:96)
227==190== Block was alloc'd at
228==190== at 0x483C583: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
229==190== by 0x109761: ds::AList<int>::AList(unsigned long) (AList.h:47)
230==190== by 0x10939F: main (test_driver.cpp:55)
231==190==
main program:
#define CATCH_CONFIG_MAIN
#include "AList.h"
#include "catch.hpp"
#include <cstdlib>
#define SIZE 5
TEST_CASE("All") {
ds::AList<int> L;
// randomly add SIZE ints to the array
int nums[SIZE];
srand(time(0)); // setting the seed for rand()
for (int i = 0; i < SIZE; i++) {
nums[i] = rand() % 20 + 1; // generating random numbers by rand()
L.addLast(nums[i]);
}
SECTION("copy constructor") {
ds::AList<int> *K = new ds::AList<int>(L);
CHECK(L.size() == K->size());
CHECK(K->getLast() == nums[SIZE - 1]);
delete K; // this should not also delete L
}
SECTION("addFirst") {
L.addFirst(123);
L.addFirst(234);
CHECK(L.getFirst() == 234);
CHECK(L.get(2) == nums[0]);
}
SECTION("removeFirst") {
int x = L.removeFirst();
CHECK(x == nums[0]);
CHECK(L.getLast() == nums[SIZE - 1]);
}
}
If anyone could give any tips or suggestions on how I can fix this, it would be greatly appreciated!

Locating C++ Memory Leak

I am currently working on a Vector class. I am required to use certain concepts such as templates, etc. For the most part I have completed the entire project, except there is a memory leak in which I'm unable to locate.
I'm using macOS Catalina and I've tried to install Valgrind however I cannot seem to get it to work. That is another issue in and of itself. Where is the memory leak located? And what is an easy way to detect where memory leaks are for macOS Catalina users?
I'm also using VS Code.
HEADER FILE
Note: ContainerIfc is an abstract class, all methods are implemented below that are needed to understand.
#ifndef PROJ7_MYVECTOR
#define PROJ7_MYVECTOR
#include "proj7-ContainerIfc.h"
template <class T>
class MyVector : public ContainerIfc<T>
{
public:
/**
* MyVector
*
* This is the default constructor that sets size equal
* to 0 and capacity to 10.
*
* Parameters: none
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
MyVector();
/**
* ~MyVector
*
* This is the destructor that deletes memory
*
* Parameters: none
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
~MyVector();
/**
* MyVector
*
* This is the copy constructor
*
* Parameters:
* v: the object that you want to copy over
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
MyVector(const MyVector &);
/**
* = operator
*
* This is the overloaded assignment operator
*
* Parameters:
* v: the object that you want to copy over
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
MyVector<T> &operator=(const MyVector &);
/**
* pushFront
*
* Prepends a value to the array
*
* Parameters:
* e: The value that you want to prepend
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
MyVector<T> &pushFront(T);
/**
* pushBack
*
* Appends a vlue to the array
*
* Parameters:
* e: The value that you want to append
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
MyVector<T> &pushBack(T);
/**
* popFront
*
* Removes the first index of the array and shifts all elements leftward
*
* Parameters:
* e: The value that was removed
*
* Output:
* return: none
* reference parameters: e
* stream: none
*/
MyVector<T> &popFront(T &);
/**
* popBack
*
* Removes the last index of the array
*
* Parameters:
* e: The value that was removed
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
MyVector<T> &popBack(T &);
/**
* front
*
* Returns the first element of the array
*
* Parameters: none
*
* Output:
* return: Copy of the first data item in the MyVector
* reference parameters: none
* stream: none
*/
T front();
/**
* back
*
* Returns the last element of the array
*
* Parameters: none
*
* Output:
* return: Returns a copy of the last data item in MyVector
* reference parameters: none
* stream: none
*/
T back();
/**
* [] operator
*
* Returns a reference to data element n in MyVector
*
* Parameters:
* n: index of item to return
*
* Output:
* return: Returns a reference to data element n in MyVector
* reference parameters: none
* stream: none
*/
T &operator[](int);
/**
* getSize
*
* Returns size of MyVector array
*
* Parameters: none
*
* Output:
* return: an integer value representing the number of elements in the list
* reference parameters: none
* stream: none
*/
int getSize();
/**
* isEmpty
*
* Returns state information about the list
*
* Parameters: none
*
* Output:
* return: Returns state information about the list
* reference parameters: none
* stream: none
*/
bool isEmpty();
/**
* erase
*
* Erases a vector
*
* Parameters: none
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
void erase();
private:
T *data;
int size;
int capacity;
/**
* grow
*
* Increases the capacity of data by doubling the previous value and allocating
* the appropriate memory for data
*
* Parameters: none
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
void grow();
/**
* shiftRight
*
* Shifts all values in the array one space to the right
*
* Parameters: none
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
void shiftRight();
/**
* shiftLeft
*
* Shifts all values in the array one space to the left
*
* Parameters: none
*
* Output:
* return: none
* reference parameters: none
* stream: none
*/
void shiftLeft();
};
template <class T>
MyVector<T>::MyVector()
{
this->size = 0;
this->capacity = 10;
this->data = new T[this->capacity];
}
template <class T>
MyVector<T>::~MyVector()
{
delete[] this->data;
}
template <class T>
MyVector<T>::MyVector(const MyVector &v)
{
this->size = v.size;
this->capacity = v.capacity;
this->data = new T[this->capacity];
// Copy each array item over
for (int i = 0; i < this->size; i++)
{
this->data[i] = v.data[i];
}
}
template <class T>
MyVector<T> &MyVector<T>::operator=(const MyVector &v)
{
this->size = v.size;
this->capacity = v.capacity;
this->data = new T[this->capacity];
// Copy each array item over
for (int i = 0; i < this->size; i++)
{
this->data[i] = v.data[i];
}
return *this;
}
template <class T>
MyVector<T> &MyVector<T>::pushFront(T e)
{
// Resize if necessary
if (this->size == this->capacity)
{
this->grow();
}
// Shift elements to the right
this->shiftRight();
// Add new value to first index of array
this->data[0] = e;
// Increment size
this->size++;
return *this;
}
template <class T>
MyVector<T> &MyVector<T>::pushBack(T e)
{
// Resize if necessary
if (this->size == this->capacity)
{
this->grow();
}
// Add value to array
this->data[this->size] = e;
// Increment size
this->size++;
return *this;
}
template <class T>
MyVector<T> &MyVector<T>::popFront(T &e)
{
// Throw BADINDEX if empty
if (this->size <= 0)
{
throw BADINDEX();
}
// Set e equal to the first value
e = this->front();
// Shift elements to the left removing the first index
this->shiftLeft();
// Decrement size
this->size--;
return *this;
}
template <class T>
MyVector<T> &MyVector<T>::popBack(T &e)
{
// Throw BADINDEX if empty
if (this->size <= 0)
{
throw BADINDEX();
}
// Set e equal to the last value
e = this->back();
// Remove last element by creating new array and copying values
T *temp = new T[this->capacity];
// Ignore last element and copy all values
for (int i = 0; i < this->size - 1; i++)
{
temp[i] = this->data[i];
}
// Deallocate current array
delete[] this->data;
// Allocate new temp array
this->data = temp;
// Decrement size
this->size--;
return *this;
}
template <class T>
T MyVector<T>::front()
{
// Throw BADINDEX if empty
if (this->size <= 0)
{
throw BADINDEX();
}
return this->data[0];
}
template <class T>
T MyVector<T>::back()
{
// Throw BADINDEX if empty
if (this->size <= 0)
{
throw BADINDEX();
}
return this->data[this->size - 1];
}
template <class T>
T &MyVector<T>::operator[](int n)
{
// Throw BADINDEX if n doesn't exist
if (n > this->size - 1)
{
throw BADINDEX();
}
return this->data[n];
}
template <class T>
int MyVector<T>::getSize()
{
return this->size;
}
template <class T>
bool MyVector<T>::isEmpty()
{
bool isEmpty = true;
// Check if size is greater than 0
if (this->size > 0)
{
isEmpty = true;
}
return isEmpty;
}
template <class T>
void MyVector<T>::erase()
{
// Erase vector by deallocating and allocating a new one
// Reset size & capacity
this->size = 0;
this->capacity = 10;
// Create new empty array
T *temp = new T[this->capacity];
// Delete old array
delete[] this->data;
// Set current array to new array
this->data = temp;
}
template <class T>
void MyVector<T>::grow()
{
// Double capacity as instructions say
this->capacity *= 2;
T *temp = new T[this->capacity];
// Copy each array item over
for (int i = 0; i < this->size; i++)
{
temp[i] = this->data[i];
}
// Deallocate current array
delete[] this->data;
// Allocate new temp array
this->data = temp;
}
template <class T>
void MyVector<T>::shiftRight()
{
// Create a new array
T *temp = new T[this->capacity];
// Copy values over shifting one to the right
for (int i = 1; i < this->size + 1; i++)
{
temp[i] = this->data[i - 1];
}
// Deallocate current array
delete[] this->data;
// Allocate new temp array
this->data = temp;
}
template <class T>
void MyVector<T>::shiftLeft()
{
// Create new array
T *temp = new T[this->capacity];
for (int i = 1; i < this->size; i++)
{
temp[i - 1] = this->data[i];
}
// Deallocate current array
delete[] this->data;
// Allocate new temp array
this->data = temp;
}
#endif
TEST FILE
#include <iostream>
#include "proj7-MyVector.h"
using namespace std;
int main()
{
cout << "MyVector Test" << endl;
cout << "Testing all functions using int MyVector, string MyVector, and double MyVector" << endl;
cout << endl;
cout << "Testing Default Constructor: ";
MyVector<int> intVector;
MyVector<string> stringVector;
MyVector<double> doubleVector;
cout << "Pass" << endl;
cout << "Testing pushFront: ";
intVector.pushFront(1);
stringVector.pushFront("test");
doubleVector.pushBack(1.32);
cout << "Pass" << endl;
cout << "Testing [] operator: ";
if (intVector[0] == 1 && stringVector[0] == "test" && doubleVector[0] == 1.32)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing pushBack: ";
intVector.pushBack(22);
stringVector.pushBack("hello");
doubleVector.pushBack(8.21);
cout << "Pass" << endl;
cout << "Testing back: ";
if (intVector.back() == 22 && stringVector.back() == "hello" && doubleVector.back() == 8.21)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing front: ";
if (intVector.front() == 1 && stringVector.front() == "test" && doubleVector.front() == 1.32)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing popFront: ";
int removedInt;
string removedString;
double removedDouble;
intVector.popFront(removedInt);
stringVector.popFront(removedString);
doubleVector.popFront(removedDouble);
if (removedInt == 1 && removedString == "test" && removedDouble == 1.32)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing getSize: ";
if (intVector.getSize() == 1 && stringVector.getSize() == 1 && doubleVector.getSize() == 1)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing popBack: ";
intVector.popBack(removedInt);
stringVector.popBack(removedString);
doubleVector.popBack(removedDouble);
if (removedInt == 22 && removedString == "hello" && removedDouble == 8.21)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing isEmpty: ";
if (intVector.isEmpty() && stringVector.isEmpty() && doubleVector.isEmpty())
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing = operator: ";
for (int i = 0; i < 10; i++)
{
intVector.pushBack(i);
stringVector.pushBack("a");
doubleVector.pushBack(2.5);
}
MyVector<int> intVector2;
MyVector<string> stringVector2;
MyVector<double> doubleVector2;
intVector2 = intVector;
stringVector2 = stringVector;
doubleVector2 = doubleVector;
if (intVector2.front() == 0 && stringVector2.front() == "a" && doubleVector2.front() == 2.5)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing copy constructor: ";
MyVector<int> intVector3(intVector2);
MyVector<string> stringVector3(stringVector2);
MyVector<double> doubleVector3(doubleVector2);
if (intVector2.front() == 0 && stringVector2.front() == "a" && doubleVector2.front() == 2.5)
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "Testing erase: ";
intVector3.erase();
stringVector3.erase();
doubleVector3.erase();
if (intVector3.isEmpty() && stringVector3.isEmpty() && doubleVector3.isEmpty())
{
cout << "Pass" << endl;
}
else
{
cout << "Fail" << endl;
}
cout << "If all of the above pass, grow(), shiftRight() and shiftLeft() are assumed passing." << endl;
return 0;
}
template <class T>
MyVector<T> &MyVector<T>::operator=(const MyVector &v)
{
this->size = v.size;
this->capacity = v.capacity;
this->data = new T[this->capacity];
The previously allocated this->data gets leaked here. It's already allocated.
Furthermore, most of the class methods needlessly new a new temp buffer, copy data to it, and delete the old data and then replace it with the newly-allocated temp buffer.
This is needless work since, it looks like, most of these operations can be done in place. Furthermore, it appears that at least one of these has a bug that will result in memory corruption under certain conditions. In your shiftRight:
for (int i = 1; i < this->size + 1; i++)
{
temp[i] = this->data[i - 1];
}
This is going to assign something to temp[this->size]. If this->size happens to be equal to this->capacity, since temp is allocated to be this->capacity in size, this is going to result in a rather nasty demon flying out of your nose, since temp[this->size] does not exist.

Error Adding Multiple Items to a Priority Queue with a Fixed Size Array

before we get started, yes this is homework.
hopefully I can get some clarification here. I am implementing a priority queue with a fixed size array and have all the functions written and everything compiles but I am having a problem with the option M in the test file. All the other functions work just fine but when I try to add_multiple_items I get an expression error in the assert of the swap_with_parent function. here is my program files. The pqtest2.cpp file:
// FILE: pqtest2.cpp
// An interactive test program for the Priority Queue class
#include <cctype> // Provides toupper
#include <iostream> // Provides cout and cin
#include <cstdlib> // Provides EXIT_SUCCESS and size_t
#include "pqueue2.h" // Implemented using a heap
using namespace std;
// PROTOTYPES for functions used by this test program:
void print_menu( );
char get_user_command( );
int get_number(const char message[ ]);
void add_multiple_entries(PriorityQueue &q);
int main( )
{
PriorityQueue test;
char choice;
cout << "CSC-161 Lesson Ten Test Program" << endl << endl;
do
{
print_menu( );
choice = toupper(get_user_command( ));
switch (choice)
{
case 'E':
if (test.is_empty( ))
cout << "The Priority Queue is empty." << endl;
else
cout << "The Priority Queue is not empty." << endl;
break;
case 'G':
if (!test.is_empty( ))
cout << "Front item is: " << test.get_front( ) << endl;
else
cout << "There is no current item." << endl;
break;
case 'I':
test.insert(get_number("Please enter the next item: "),
(unsigned int) get_number("The item's priority: "));
break;
case 'M':
add_multiple_entries(test);
break;
case 'P':
test.print_tree("Contents of heap:");
break;
case 'S':
cout << "The size is " << test.size( ) << endl;
break;
case 'X':
if (test.is_empty( ))
cout << "The Priority Queue is empty." << endl;
else
while(!test.is_empty())
cout << "Value: " << test.get_front() << endl;
break;
case 'Q':
break;
default:
cout << choice << " is an invalid choice." << endl;
}
}
while ((choice != 'Q'));
return EXIT_SUCCESS;
}
void print_menu( )
{
cout << endl;
cout << "The following choices are available: " << endl;
cout << " E Print the result from the is_empty( ) function" << endl;
cout << " G Print the result from the get_front( ) function" << endl;
cout << " I Insert a new item with the insert(...) function" << endl;
cout << " M Add multiple items with varying priorities " << endl;
cout << " P Print the internal heap using the print_tree(...) function" << endl;
cout << " S Print the result from the size( ) function" << endl;
cout << " X Extract and print values in priority order" << endl;
cout << " Q Quit this test program" << endl;
}
char get_user_command( )
{
char command;
cout << "\nEnter choice: ";
cin >> command;
return command;
}
int get_number(const char message[ ])
{
int result;
cout << message;
cin >> result;
return result;
}
void add_multiple_entries(PriorityQueue &thisQueue)
{
thisQueue.insert(100, 10);
thisQueue.insert(200, 10);
thisQueue.insert(300, 5);
thisQueue.insert(400, 5);
thisQueue.insert(500, 20);
thisQueue.insert(600, 20);
thisQueue.insert(700, 20);
thisQueue.insert(800, 10);
thisQueue.insert(900, 10);
return;
}
The pqueue.h file:
// FILE: pqueue2.h
// CLASS PROVIDED: PriorityQueue (a priority queue of items)
//
// TYPEDEF and MEMBER CONSTANT for the PriorityQueue class:
// static const size_t CAPACITY = ______
// PriorityQueue::CAPACITY is the maximum number of entries that
// may be be in the priority queue at any one time.
//
// typedef _____ Item
// The type Item is the data type of the items in the Priority Queue.
// It may be any of the C++ built-in types (int, char, etc.), or a class
// with a default constructor, a copy constructor, and assignment operator.
//
// CONSTRUCTOR for the PriorityQueue class:
// PriorityQueue( )
// Postcondition: The PriorityQueue has been initialized with no Items.
//
// MODIFICATION MEMBER FUNCTIONS for the PriorityQueue class:
// void insert(const Item& entry, unsigned int priority)
// Postcondition: A new copy of entry has been inserted with the specified
// priority.
//
// Item get_front( )
// Precondition: size( ) > 0.
// Postcondition: The highest priority item has been returned and has been
// removed from the PriorityQueue. (If several items have equal priority,
// then there is no guarantee about which one will come out first!
// This differs from our first priority queue.)
//
// CONSTANT MEMBER FUNCTIONS for the PriorityQueue class:
// size_t size( ) const
// Postcondition: Return value is the total number of items in the
// PriorityQueue.
//
// bool is_empty( ) const
// Postcondition: Return value is true if the PriorityQueue is empty.
//
// VALUE SEMANTICS for the PriorityQueue class:
// Assignments and the copy constructor may be used with
// PriorityQueue objects
#ifndef PQUEUE_H
#define PQUEUE_H
#include <cstdlib> // Provides size_t
class PriorityQueue
{
public:
// TYPEDEF and MEMBER CONSTANT
typedef double Item;
static const size_t CAPACITY = 5000;
// CONSTRUCTOR
PriorityQueue( );
// MODIFICATION MEMBER FUNCTIONS
void insert(const Item& entry, unsigned int priority);
Item get_front( );
// CONSTANT MEMBER FUNCTIONS
size_t size( ) const { return many_items; }
bool is_empty( ) const { return (many_items == 0); }
// MEMBER FUNCTION FOR DEBUGGING
void print_tree(const char message[ ] = "", size_t i = 0) const;
private:
// STRUCT DEFINITION to store information about one item in the pqueue
struct OneItemInfo
{
Item data;
unsigned int priority;
};
// PRIVATE MEMBER VARIABLES
OneItemInfo heap[CAPACITY];
size_t many_items;
// PRIVATE HELPER FUNCTIONS -- see pqueue2.cxx for documentation
bool is_leaf(size_t i) const;
size_t parent_index(size_t i) const;
unsigned int parent_priority(size_t i) const;
size_t big_child_index(size_t i) const;
unsigned int big_child_priority(size_t i) const;
void swap_with_parent(size_t i);
};
#endif
The pqueue2.cpp file:
// FILE: pqueue2.cpp
// IMPLEMENTS: PriorityQueue (See pqueue2.h for documentation.)
// IMPLEMENTED BY: Michael Main (main#colorado.edu)
//
// Alex Chapman ID: S02084651
//
//
// INVARIANT for the PriorityQueue Class:
// 1. The member variable many_items is the number of items in the
// PriorityQueue.
// 2. The items themselves are stored in the member variable heap,
// which is a partially filled array organized to follow the usual
// heap storage rules from Chapter 11 of the class notes.
// NOTE: Private helper functions are implemented at the bottom of this
// file along with their precondition/postcondition contracts.
#include <cassert> // Provides assert function
#include <iostream> // Provides cin, cout
#include <iomanip> // Provides setw
#include <cmath> // Provides log2
#include "pqueue2.h"
using namespace std;
PriorityQueue::PriorityQueue( )
{
heap[CAPACITY];
many_items = 0;
}
void PriorityQueue::insert(const Item& entry, unsigned int priority)
{
if (many_items == 0)
{
heap[many_items].data = entry;
heap[many_items].priority = priority;
many_items++;
}
else
{
heap[many_items].data = entry;
heap[many_items].priority = priority;
unsigned int i = many_items;
many_items++;
while(parent_priority(i) < priority)
{
swap_with_parent(i);
i = parent_index(i);
}
}
}
PriorityQueue::Item PriorityQueue::get_front( )
{
assert(many_items > 0);
if (many_items == 1)
{
Item front_value = heap[0].data;
many_items--;
return front_value;
}
else
{
Item front_value = heap[0].data;
heap[0] = heap[many_items - 1];
unsigned int priority = heap[many_items - 1].priority;
unsigned int k = 0;
while((k < many_items) && !is_leaf(k) && big_child_priority(k) > priority)
{
unsigned int j = big_child_index(k);
swap_with_parent(big_child_index(k));
k = j;
}
many_items--;
return front_value;
}
}
bool PriorityQueue::is_leaf(size_t i) const
// Precondition: (i < many_items)
// Postcondition: If heap[i] has no children in the heap, then the function
// returns true. Otherwise the function returns false.
{
if (2 * i + 1 >= many_items)
{
return 1;
}
else
{
return 0;
}
}
size_t PriorityQueue::parent_index(size_t i) const
// Precondition: (i > 0) && (i < many_items)
// Postcondition: The return value is the index of the parent of heap[i].
{
return (i - 1) / 2;
}
unsigned int PriorityQueue::parent_priority(size_t i) const
// Precondition: (i > 0) && (i < many_items)
// Postcondition: The return value is the priority of the parent of heap[i].
{
return heap[(i - 1) / 2].priority;
}
size_t PriorityQueue::big_child_index(size_t i) const
// Precondition: !is_leaf(i)
// Postcondition: The return value is the index of one of heap[i]'s children.
// This is the child with the larger priority.
{
assert(!is_leaf(i));
if ((2 * i) + 2 < many_items)
{
if (heap[(2 * i) + 1].priority > heap[(2 * i) + 2].priority)
{
return (2 * i) + 1;
}
else
{
return (2 * i) + 2;
}
}
else
{
return (2 * i) + 1;
}
}
unsigned int PriorityQueue::big_child_priority(size_t i) const
// Precondition: !is_leaf(i)
// Postcondition: The return value heap[big_child_index(i)].priority
{
return heap[big_child_index(i)].priority;
}
void PriorityQueue::swap_with_parent(size_t i)
// Precondition: (i > 0) && (i < many_items)
// Postcondition: heap[i] has been swapped with heap[parent_index(i)]
{
assert (i>0 && i< many_items);
OneItemInfo temp_parent = heap[parent_index(i)];
OneItemInfo temp_child = heap[i];
heap[i] = temp_parent;
heap[parent_index(i)] = temp_child;
}
void PriorityQueue::print_tree(const char message[ ], size_t i) const
// Postcondition: If the message is non-empty, then that has been written
// to cout. After the message, the portion of the heap with root at node
// node i has been written to the screen. Each node's data is indented
// 4*d, where d is the depth of the node.
// NOTE: The default argument for message is the empty string, and the
// default argument for i is zero. For example, to print the entire
// tree of a PriorityQueue p, with a message of "The tree:", you can call:
// p.print_tree("The tree:");
// This call uses i=0, which prints the whole tree.
{
const char NO_MESSAGE[] = "";
size_t depth;
if (message[0] != '\0')
{
cout << message << endl;
}
if (i > many_items)
{
cout << "No Nodes" << endl;
}
else
{
depth = int(log(double(i + 1))/log(2.0));
cout << setw(depth * 4) << "";
cout << heap[i].data;
cout << " (priority " << heap[i].priority << ")" << endl;
if (2 * i + 1 < many_items)
{
print_tree(NO_MESSAGE, 2 * i + 1);
}
if (2 * i + 2 < many_items)
{
print_tree(NO_MESSAGE, 2 * i + 2);
}
}
}
Also I have attached the error pic.
while(parent_priority(i) < priority)
You kept looking for parent even when i == 0. Change it into while (i > 0 && parent_priority(i) < priority).

Heap memory corruption c++ templated class

I'm just a humble student looking to further my knowledge about the C++ language. My professor isn't helping! I think the title along with comments in-code explain my issues clearly.
#ifndef H_Htable
#define H_Htable
//****************************************************************
// Author: D.S. Malik
//
// This class specifies the members to implement a hash table as
// an ADT. It uses quadratic probing to resolve collisions.
//****************************************************************
#include <iostream>
#include <cassert>
using namespace std;
template <class elemType>
class hashT
{
public:
void insert(int hashIndex, const elemType& rec);
//Function to insert an item in the hash table. The first
//parameter specifies the initial hash index of the item to
//be inserted. The item to be inserted is specified by the
//parameter rec.
//Postcondition: If an empty position is found in the hash
// table, rec is inserted and the length is incremented by
// one; otherwise, an appropriate error message is
// displayed.
//sequential search
bool search(int& hashIndex, const elemType& rec, bool found = false) const;
//Function to determine whether the item specified by the
//parameter rec is in the hash table. The parameter hashIndex
//specifies the initial hash index of rec.
//Postcondition: If rec is found, found is set to true and
// hashIndex specifies the position where rec is found;
// otherwise, found is set to false.
bool isItemAtEqual(int hashIndex, const elemType& rec) const;
//Function to determine whether the item specified by the
//parameter rec is the same as the item in the hash table
//at position hashIndex.
//Postcondition: Returns true if HTable[hashIndex] == rec;
// otherwise, returns false.
void retrieve(int hashIndex, elemType& rec) const;
//Function to retrieve the item at position hashIndex.
//Postcondition: If the table has an item at position
// hashIndex, it is copied into rec.
void remove(int hashIndex, const elemType& rec);
//Function to remove an item from the hash table.
//Postcondition: Given the initial hashIndex, if rec is found
// in the table it is removed; otherwise, an appropriate
// error message is displayed.
void print() const;
//Function to output the data.
//provide for both int and string data types in the hash table
hashT(int size = 101, bool isIntTable = true);
//constructor
//Postcondition: Create the arrays HTTable and indexStatusList;
// initialize the array indexStatusList to 0; length = 0;
// HTSize = size; and the default array size is 101.
~hashT();
//destructor
//Postcondition: Array HTable and indexStatusList are deleted.
private:
elemType *HTable; //pointer to the hash table
int *indexStatusList; //pointer to the array indicating the
//status of a position in the hash table
int length; //number of items in the hash table
int HTSize; //maximum size of the hash table
};
template <class elemType>
void hashT<elemType>::insert(int hashIndex, const elemType& rec)
{
int pCount;
int inc;
pCount = 0;
inc = 1;
while (indexStatusList[hashIndex] == 1
&& HTable[hashIndex] != rec
&& pCount < HTSize / 2)
{
pCount++;
hashIndex = (hashIndex + inc) % HTSize;
inc = inc + 2;
}
if (indexStatusList[hashIndex] != 1)
{
HTable[hashIndex] = rec;
indexStatusList[hashIndex] = 1;
length++;
}
else
if (HTable[hashIndex] == rec)
cerr << "Error: No duplicates are allowed." << endl;
else
cerr << "Error: The table is full. "
<< "Unable to resolve the collision." << endl;
}
//sequential search
template <class elemType>
bool hashT<elemType>::search(int& hashIndex, const elemType& rec, bool found) const
{
for (int i = 0; i < HTSize; i++) {
if (HTable[i] == rec) { //assuming no repeat data
found = true;
hashIndex = i;
break;
}
}
return found;
}
template <class elemType>
bool hashT<elemType>::isItemAtEqual(int hashIndex, const elemType& rec) const
{
//first make sure the item has not been removed
if (indexStatusList[hashIndex] != -1) {
//make equality comparison
if (HTable[hashIndex] == rec)
return true;
else
return false; //comparison fails
}
else
{
std::cerr << "isItemEqual(): Item has been removed" << endl;
return false;
}
}
template <class elemType>
void hashT<elemType>::retrieve(int hashIndex, elemType& rec) const
{
if (indexStatusList[hashIndex] != -1)
rec = HTable[hashIndex];
else
std::cerr << "retrieve(): item has been removed" << endl;
}
template <class elemType>
void hashT<elemType>::remove(int hashIndex, const elemType& rec)
{
//make sure the item hasn't already been removed
if (indexStatusList[hashIndex] != -1) {
bool isInList = hashT<elemType>::search(hashIndex, rec);
//update the status
if (isInList)
{
indexStatusList[hashIndex] = -1;
length--; //decrement length
}
else
std::cerr << "hasT::remove() could not remove the specified item" << endl;
}
else
{
std::cerr << "remove(): Item has already been removed from the table" << endl;
}
}
template <class elemType>
void hashT<elemType>::print() const
{
std::cout << "Hash Table Data: " << endl;
for (int i = 0; i < (length - 5); i++) {
elemType item = HTable[i];
//std::cout << item << " ";
}
}
template <class elemType>
hashT<elemType>::hashT(int size, bool isIntTable)
{
HTable = new elemType[]; //is this right? HTable is an array just like indexStatusList
HTSize = size;
length = 0;
indexStatusList = new int[0]; //I think this one works?
}
template <class elemType>
hashT<elemType>::~hashT() //deleting always causes heap errors!!!
//says writing to unallocated memory -- debugging shows otherwise
{
//delete[] HTable;
//delete[] indexStatusList; //still causing errors -- error now not associated with any particular line (of my code)
}
#endif
I've kept increasing my bounds checking security when instantiating hashT in main. I'm convinced it is because my data members are being initialized incorrectly. This is one error message I get after trying a few things: "Unhandled exception at 0x773F627C (ntdll.dll) in exercise7Chap9.exe: 0xC0000374: A heap has been corrupted (parameters: 0x77426480)."
finally, here's main just in case:
#include <iostream>
#include "hashT.h"
int main() {
//add one item and test for equality
//hashT<int> ht = hashT<int>(20);
//ht.insert(0, 1);
//bool itemInsertSuccess = ht.isItemAtEqual(0, 1);
//if (itemInsertSuccess)
// std::cout << "first test has succeeded" << endl;
//else
// std::cout << "first test has failed" << endl;
////remove item and make sure isItemEqual returns false
//ht.remove(0, 1);
//bool itemRemoved = ht.isItemAtEqual(0, 1);
//if (!itemRemoved)
// std::cout << "second test passed" << endl;
//else
// std::cout << "second test failed" << endl;
//add many items then make sure search() works
hashT<int> ht1 = hashT<int>(51);
for (int i = 0; i < 10; i++)
ht1.insert(i, i);
int indx = -1;
ht1.search(indx, 0);
if (indx == 25)
std::cout << "Test 3 has passed" << endl;
else
std::cout << "Test 3 has failed" << endl;
//print data then test retrieve() and print a single item
/*ht1.print();
int item = -1;
ht1.retrieve(10, item);
if (item != -1) {
std::cout << item << endl;
std::cout << "test 4 has passed" << endl;
}
else
std::cout << "test 4 has failed" << endl;
hashT<int> HtRetrieve = hashT<int>(10);
HtRetrieve.insert(0, 0);
int it = -1;
HtRetrieve.retrieve(0, it);
std::cout << it << endl;*/
char stop;
std::cin >> stop;
//return 0;
}
In your case here, scrap the variable isIntTable. Templates are a compile-time construct and run-time values won't influence how the template is compiled into a class in any way.
Then, in your constructor, just use the template type as the one you are allocating.
template <class elemType>
hashT<elemType>::hashT(int size)
{
HTable = new elemType[size];
length = 0;
indexStatusList = new int[0];
}
However, this could be much better. Consider using initialisation instead of assignation:
hashT<elemType>::hashT(int size) :
HTable{new elemType[size]},
length{size},
indexStatusList{int[size]} { /* empty constructor */ }
And it can be even better. Consider using smart pointer instead of raw owning pointers and vectors instead of dynamic allocated array:
template<typename T>
struct hashT {
// using the right type for size
hashT(std::size_t size) : pointerToOneT{std::make_unique<T>()}, HTable(size) {}
// make_unique is the `new` for unique pointers
// no need for destructors, the vector and unique_ptr are freeing themselves
private:
std::unique_ptr<T> pointerToOneT;
std::vector<T> HTable;
std::vector<int> indexStatusList;
};
If you don't want to use std::vector, you can always use std::unique_ptr<T[]>, which is a dynamically allocated array that free itself.
template<typename T>
struct hashT {
// using the right type for size
hashT(std::size_t size) :
HTable{std::make_unique<T[]>(size)},
indexStatusList(std::make_unique<int[]>(size)) {}
private:
std::unique_ptr<T[]> HTable;
std::unique_ptr<int[]> indexStatusList;
};
EDIT
In your actual destructor, the problem is that you initialized the int* with the new[] but you are using delete. To delete an array, you must use delete[]
template <class elemType>
hashT<elemType>::~hashT()
{
delete HTable;
delete[] indexStatusList;
}
Turns out this heap corruption was caused by my lack of understanding dynamic arrays in C++.
My incorrect initialization of the arrays HTable and indexStatusList were: Htable = new elemType();, HTable = new elemType[]; and indexStatusList = new int[0];
I simply needed to add the size as an argument (never seen a size argument passed in brackets before!)
Here is the working constructor:
//constructor
template <class elemType>
hashT<elemType>::hashT(int size)
{
HTable = new elemType[size]; // pass size so the compiler knows what to allocate and deallocate
HTSize = size;
length = 0;
indexStatusList = new int[size];
}
working destructor:
template <class elemType>
hashT<elemType>::~hashT()
{
delete[] HTable;
delete[] indexStatusList;
}

C++ BAD_ACCES error (code 1)

I'm making a C++ program "Hash Table"
I've spent 2 days debugging this piece of code but I still don't understand what's wrong.
I'm using xCode and it says "Build Failed" and gives this message
Thread 1:EXC_BAD_ACCESS (code=1, address=0x110)
Here is the pieces of my code, I'd really appreciate your any help!
hash.cpp
#include "hash.h"
size_t HashTable::hash_s(const Key &k){ /* simple hash function just to see how collisions are handled */
return (k.length());
}
HashTable::HashTable(): size_(0), numberOfLoaded(0){} /* constructor */
HashTable::~HashTable() { /* destructor */
delete [] hashTable;
}
void HashTable::allocate(){ /* function for memory allocation */
if (empty()){ /* if hashTable is empty, allocate memory for one element */
size_ = 1;
hashTable = new hashTableElement[size_];
hashTable->k = nullptr;
hashTable->value = nullptr;
return;
} else { /* if hashTable is not empty (at least has 1 element */
hashTableElement *newHashTable = new hashTableElement[size_*2]; /* allocate memory for new double-sized array */
for (int i = 0; i < size_; i++ ){
if (hashTable[i].k != nullptr){ /* copy all not empty array elements into the new double-sized array */
size_t newIndex = hash_s(*(hashTable[i].k)) % (size_*2); /* count new index for double-sized array */
newHashTable[newIndex] = hashTable[i];
}
}
delete [] hashTable; /* delete memory from small table */
size_ *= 2;
hashTable = newHashTable;
}
}
bool HashTable::insert(const Key &k, const Value &v){
allocate(); /* call allocation function */
size_t index = hash_s(k) % size_; /* index is a reminder of hash_s divided by size of the table */
hashTableElement *currentElement = &hashTable[index]; /* set a pointer to the currentElement */
/*problem is here EXC_BAD ACCESS (code=1, address=0x110)*/ while (currentElement->next) currentElement = currentElement->next; /* move to the last element in collision chain */
if ((currentElement->value != nullptr) || (currentElement != &hashTable[index])){ /* allocate memory for next element */
currentElement->next = new hashTableElement;
currentElement = currentElement->next;
}
currentElement->value = new Value; /* allocate memory for structure */
currentElement->k = new Key; /* allocate memory for key */
*(currentElement->k) = k; /* set to new element key value the value of inserted element */
*(currentElement->value) = v; /* set to new element value */
numberOfLoaded++; /* increment counter of inserted elements */
return true;
}
bool HashTable::empty() const{
for (int i = 0; i < size_; i++){
if( hashTable[i].value != nullptr ){ /* if in the table at least one element inserted, return false */
return false;
}
}
return true;
}
main.cpp
#include "hash.h"
#include <fstream>
#include <iostream>
using namespace std;
void HashTable::print(){ /* function that prints entire table */
for (int i = 0; i < size_; i++){
hashTableElement *newelement = &hashTable[i]; /* set a pointer to current element */
while ((newelement) && (newelement->value != nullptr)){ /* printing all collisions chain */
cout << *(newelement->k) << " " << newelement->value->age << " " << newelement->value->weight << endl;
cout << "I = " << i << " Number Of loaded = " << numberOfLoaded << " Size of Table = "<< size_ <<endl;
cout << "_____________________"<<endl;
newelement = newelement->next; /* go to the next element in the chain */
}
}
}
int main(int argc, const char * argv[]) {
HashTable hashObj;
string name;
Value val;
Key k;
ifstream ins("/Users/Aeon/Documents/Study/NSU/Programming/Lab Works/2_Level/2_hash_table/Realization/input2.txt");
if (!ins.is_open()){
cout << "File can't be open!\n"<<endl;
} else {
while (ins >> k){ /* read a key (which is person's name) */
ins >> val.age; /* read an age */
ins >> val.weight; /* read a weight */
hashObj.insert(k, val); /* call insert function */
}
}
hashObj.print(); /* print an entire table */
return 0;
}
hash.h
#include <algorithm>
#include <stdlib.h>
#include <string>
using namespace std;
typedef std::string Key;
struct Value {
unsigned int age;
unsigned int weight;
};
struct hashTableElement {
Value *value;
Key *k;
hashTableElement *next;
};
class HashTable {
private:
unsigned int numberOfLoaded;
size_t size_;
hashTableElement *hashTable;
void allocate(); /* function for memory allocation */
public:
HashTable(); /* constructor */
~HashTable(); /* destructor */
size_t hash_s(const Key &k); /* simple hash function */
void print(); /* function prints entire table */
bool insert(const Key& k, const Value& v); /* function inserts an element into the table */
bool empty() const; /* function returns true if HashTable is empty, false if not */
};
#endif /* defined(__Lab_Hash__hash__) */
Also, I just uploaded my test files:
input2
input
Thank you very much!