I am trying to simulate Conway's game of life using an implementation file I created, I have made good progress but unfortunately I am getting an error which confuses me. I think the problem is ignorance on my part of how to properly code templated functions, anyways this is my implementation file:
#include <list>
#ifndef HashTable_h
#define HashTable_h
using namespace std;
#define HASHTABLE_CAPACITY 1009
template <class DataType>
class HashTable
{
public:
HashTable(); // constructor
bool insert(DataType &a); // insert function for inserting value of dataType into table
bool retrieve(DataType &a); // retrieve function for retrieving value from table
bool replace(DataType &a); // function for replacing the value from the table with the parameter
bool remove(DataType& a);//removed function written and checked
//int getSizeOf() const;
void clear(); // for clearing the table
int size() const;
private:
list<DataType> table[HASHTABLE_CAPACITY]; // static array
int count;
int currentIndex;
typename list<DataType>::const_iterator it;
};
// constructor
template <class DataType>
HashTable<DataType>::HashTable()
{
list<DataType> table[HASHTABLE_CAPACITY];
count = 0;
currentIndex = -1;
}
// retrieve function
template <class DataType>
bool HashTable<DataType>::retrieve(DataType &a)
{
// get wrapped index
int wrappedIndex = a.hashCode() % HASHTABLE_CAPACITY;
if (wrappedIndex < 0) wrappedIndex = wrappedIndex + HASHTABLE_CAPACITY;
// if the array location isn't occupied, fail
if (wrappedIndex < 0 || wrappedIndex >= HASHTABLE_CAPACITY || table[wrappedIndex].empty()) return false;
// iterator for traversing table values
typename list<DataType>::const_iterator it;
// if the keys match then replace the data
// if a collision occurs then return false
it = find(table[wrappedIndex].begin(), table[wrappedIndex].end(), a);
if(it == table[wrappedIndex].end())
return false;
a = *it;
return true;
}
// overloaded operator function
// function for inserting values
template <class DataType>
bool HashTable<DataType>::insert(DataType &value)
{
// get wrapped index
int wrappedIndex = value.hashCode() % HASHTABLE_CAPACITY;
if (wrappedIndex < 0) wrappedIndex = wrappedIndex + HASHTABLE_CAPACITY;
// iterator for traversing values in table
typename list<DataType>::iterator it;
// if array location is not "occupied", copy into array
// else if keys match, replace the data
if (table[wrappedIndex].empty())
{
table[wrappedIndex].push_back(value);
count++;
return true;
}
else
{
it = find(table[wrappedIndex].begin(), table[wrappedIndex].end(), value);
if (it != table[wrappedIndex].end()) *it = value;
else {table[wrappedIndex].push_back(value); count++;}
}
return true;
}
// function for replacing values
template <class DataType>
bool HashTable<DataType>::replace(DataType &value)
{
// get wrapped index
int wrappedIndex = value.hashCode() % HASHTABLE_CAPACITY;
if (wrappedIndex < 0) wrappedIndex = wrappedIndex + HASHTABLE_CAPACITY;
if(table[wrappedIndex].empty()) return false;
// iterator for traversing the values in table
typename list<DataType>::const_iterator it;
it = find(table[wrappedIndex].begin(), table[wrappedIndex].end(), value);
if(it == table[wrappedIndex].end()) return false;
value = *it;
table[wrappedIndex].erase(it);
count--;
return true;
}
template <class DataType>
bool HashTable<DataType>::remove(DataType &value)
{
// get wrapped index
int wrappedIndex = value.hashCode() % HASHTABLE_CAPACITY;
if (wrappedIndex < 0) wrappedIndex = wrappedIndex + HASHTABLE_CAPACITY;
if(table[wrappedIndex].empty()) return false;
// iterator for traversing the values in table
typename list<DataType>::iterator it;
// if array location is not "occupied", copy into array
// else if keys match, remove the data
it = find(table[wrappedIndex].begin(), table[wrappedIndex].end(), value);
if(it == table[wrappedIndex].end()) return false;
value = *it;
table[wrappedIndex].erase(it);
count--;
return true;
}
// function for clearing the table of it's values
template <class DataType>
void HashTable<DataType>::clear()
{
count = 0;
currentIndex = -1;
for(int i = 0; i < HASHTABLE_CAPACITY; i++)
if( !table[i].empty()) table[i].clear();
}
template <class DataType>
int HashTable<DataType>::size() const
{
return count;
}
#endif
And this is the actual Game Of Life driver file:
// Lab 11b
#include <iostream>
using namespace std;
struct cell
{
int value; // equal to 1, so 0,0 is not a blank
int row; // any +/0/- value
int col; // any +/0/- value
bool operator==(const cell& c) const {return row == c.row && col == c.col;}
bool operator<(const cell& c) const {return (1000000 * row + col) < (1000000 * c.row + c.col);}
int hashCode() const {return 31 * row + col;}
};
#include "HashTable.h"
HashTable<cell> grid;
HashTable<cell> newGrid;
const int MINROW = -25;
const int MAXROW = 25;
const int MINCOL = -35;
const int MAXCOL = 35;
int neighborCount(int row, int col)
{
cell temp;
int count = 0;
for (temp.row = row - 1; temp.row <= row + 1; temp.row++)
for (temp.col = col - 1; temp.col <= col + 1; temp.col++)
if (temp.row != row || temp.col != col)
if (grid.retrieve(temp))
++count;
return count;
}
void initialize()
{
cout << "List the coordinates for living cells.\n";
cout << "Terminate the list with a special pair -1 -1\n";
cell temp;
while (true)
{
cin >> temp.row >> temp.col;
if (temp.row == -1 && temp.col == -1) break;
grid.insert(temp);
}
cin.ignore();
}
void print()
{
cell temp = {1};
cout << "\nThe current Life configuration is:\n";
for (temp.row = MINROW; temp.row <= MAXROW; temp.row++)
{
for (temp.col = MINCOL; temp.col <= MAXCOL; temp.col++)
if (grid.retrieve(temp))
cout << '*';
else
cout << ' ';
cout << endl;
}
cout << endl;
}
void update()
{
cell temp = {1};
newGrid.clear();
for (temp.row = MINROW; temp.row <= MAXROW; temp.row++)
for (temp.col = MINCOL; temp.col <= MAXCOL; temp.col++)
switch (neighborCount(temp.row, temp.col))
{
case 2:
if (grid.retrieve(temp)) newGrid.insert(temp);
break;
case 3:
newGrid.insert(temp);
break;
}
grid = newGrid;
};
int main()
{
cout << "Welcome to Conway's game of Life\n";
cout << "This game uses a grid in which\n";
cout << "each cell can either be occupied by an organism or not.\n";
cout << "The occupied cells change from generation to generation\n";
cout << "according to the number of neighboring cells which are alive.\n";
initialize();
print();
for (int i = 1; grid.size(); i++)
{
cout << "Generation " << i << ". Press ENTER to continue, X-ENTER to quit...\n";
if (cin.get() > 31) break;
update();
print();
}
return 0;
}
When I try to compile these files I get this error:
In file included from GameOfLife.cpp:16:
HashTable.h: In member function ‘bool HashTable<DataType>::retrieve(DataType&) [with DataType = cell]’:
GameOfLife.cpp:32: instantiated from here
HashTable.h:74: error: no matching function for call to ‘find(std::_List_iterator<cell>, std::_List_iterator<cell>, cell&)’
HashTable.h: In member function ‘bool HashTable<DataType>::insert(DataType&) [with DataType = cell]’:
GameOfLife.cpp:47: instantiated from here
HashTable.h:117: error: no matching function for call to ‘find(std::_List_iterator<cell>, std::_List_iterator<cell>, cell&)’
What could be the issue here?
You need to #include <algorithm> to get std::find. This is presumably what you want to use when you call find. You should avoid using namespace std, specially in headers.
Related
So I'm trying to create this priority queue to handle my "Order" objects, I'm running into a problem where an object containing the same key/priority will be placed at an early earlier position than others initialized first. I have provided the expected and received output alongside the 83 lines of code of how I constructed my heap with notes
#include <iostream>
#include <vector>
struct Order {
int value = -1;
int priority = -1;
bool operator <(Order const& RHS) { return priority < RHS.priority; }
};
class heap {
private:
std::vector<Order> orders{ Order{} };
int size{}; //initalizes it at 0
int p(int index) { return index >> 1; }
int l(int index) { return index << 1; }
int r(int index) { return (index << 1) + 1; }
public:
bool isEmpty() const { return size == 0; }
void shiftUp(int position);
void shiftDown(int position);
void add(Order new_entry);
Order removeTop();
Order& getTop() { return orders[1]; }
};
template <typename T>
void mySwap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
heap h;
h.add(Order{1,3}); h.add(Order{2,2});
h.add(Order{3,3}); h.add(Order{5,1});
h.add(Order{6,2}); h.add(Order{7,2});
h.add(Order{8,3}); h.add(Order{9,1});
h.add(Order{23,3});
std::cout << "value" << " key(priority)" << "\n";
for (int i = 0; i < 8; i++) {
Order temp = h.removeTop();
std::cout << temp.value << "\t " << temp.priority << "\n";
}
}
void heap::shiftUp(int position) {
if (position > size) return;
if (position == 1) return;
if (orders[p(position)] < orders[position]) {
mySwap(orders[position], orders[p(position)]);
shiftUp(p(position));
}
}
void heap::shiftDown(int position) {
if (position > size) return;
int greaterPosition = position;
if (l(position) <= size && orders[position] < orders[l(position)])
greaterPosition = l(position);
if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
greaterPosition = r(position);
if (greaterPosition != position) {
mySwap(orders[position], orders[greaterPosition]);
shiftDown(greaterPosition);
}
}
void heap::add(Order new_entry) {
if (size + 1 >= orders.size()) orders.push_back(Order{});
orders[++size] = new_entry;
shiftUp(size);
}
Order heap::removeTop() {
Order temp = orders[1];
mySwap(orders[1],orders[orders.size() - 1]); size--;
orders.pop_back();
shiftDown(1);
return temp;
}
/*
Expected Output
Value key(priority)
1 3
3 3
8 3
23 3
2 2
6 2
7 2
5 1
9 1
Recieved/wrong Output
value key(priority)
1 3
23 3
3 3
8 3
2 2
6 2
7 2
5 1
*/
Fixed code from answered information above
#include <iostream>
#include <vector>
struct Order {
int value = -1;
int priority = -1;
int FIFO;
bool operator <(Order const& RHS) {
if (priority == RHS.priority)
return FIFO > RHS.FIFO;
else
return priority < RHS.priority;
} //compares keys for larger presidence
};
class heap {
private:
std::vector<Order> orders{ Order{} };
int size{}; //initalizes it at 0
int p(int index) { return index >> 1; }
int l(int index) { return index << 1; }
int r(int index) { return (index << 1) + 1; }
public:
bool isEmpty() const { return size == 0; }
void shiftUp(int position);
void shiftDown(int position);
void add(Order new_entry);
Order removeTop();
Order& getTop() { return orders[1]; }
};
template <typename T>
void mySwap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
int main() {
heap h;
h.add(Order{1,3}); h.add(Order{2,2});
h.add(Order{3,3}); h.add(Order{5,1});
h.add(Order{6,2}); h.add(Order{7,2});
h.add(Order{8,3}); h.add(Order{9,1});
h.add(Order{23,3});
std::cout << "value" << " key(priority)" << "\n";
for (int i = 0; i < 8; i++) {
Order temp = h.removeTop();
std::cout << temp.value << "\t " << temp.priority << "\n";
}
}
void heap::shiftUp(int position) {
if (position > size) return;
if (position == 1) return;
if (orders[p(position)] < orders[position]) {
mySwap(orders[position], orders[p(position)]);
shiftUp(p(position));
}
}
void heap::shiftDown(int position) {
if (position > size) return;
int greaterPosition = position;
if (l(position) <= size && orders[position] < orders[l(position)])
greaterPosition = l(position);
if (r(position) <= size && orders[greaterPosition] < orders[r(position)])
greaterPosition = r(position);
if (greaterPosition != position) {
mySwap(orders[position], orders[greaterPosition]);
shiftDown(greaterPosition);
}
}
void heap::add(Order new_entry) {
if (size + 1 >= orders.size()) orders.push_back(Order{});
new_entry.FIFO = size + 1;
orders[++size] = new_entry;
shiftUp(size);
}
Order heap::removeTop() {
Order temp = orders[1];
mySwap(orders[1],orders[orders.size() - 1]); size--;
orders.pop_back();
shiftDown(1);
return temp;
}
In general, heap does not have FIFO property until you implement something that helps doing so. In your order class, you are only comparing using the priority value. In your Order class, you are comparing two Orders by only their priority value. You need a additional variable that serves as the purpose for recording the timing when that value was inserted, and compare according to that.
If you are using the variable value for that purpose, you need to specify in your overloaded < method, what do you want to do when two Order's priority values are equal. Currently, you are only using the priority variable to compare. You are not specifying what do you want to do when the priority of two Orders are equal. You have to specify what do you want to do when the priority value of two variables are equal. Maybe compare a timing variable.
I am required to implement a dynamic array that adjusts, dynamically, in accordance with the number of value (temperatures) that are input into the code. I have written the majority of the code for this to be possible, however I have run into a bug and for the life of me, have been unable to locate the issue.
The program is supposed to output the values of temp_a, make temp_b = temp_a, output the value of temp_b, and then clear the value of temp_a, and finally output the values of temp_b once more.
However, when I compile the program, it outputs that the list is full and cannot add any more values, meaning there is a logic error somewhere in the code.
Please forgive me for the lengthy code, as soon as I can locate the error, the code shall be separated into multiple compilations.
#include <iostream>
using namespace std;
class TemperatureList {
private:
int* temp; // pointer to dynamic array
short current_size; // current number of elements
short max_size; // max number of elements allowed in this list
public:
// Overloading assignment operator
void operator =(const TemperatureList& another_list);
// === Constructors ===
// Default constructor
TemperatureList();
// Constructor that accepts an integer parameter that specifies the max length of the list
TemperatureList(int max);
// Copy constructor that accepts another List as parameter
TemperatureList(const TemperatureList& another_list);
// Destructor
~TemperatureList();
// === Modifier functions ===
// add new_value to end of list if there is still space
void add_temperature(int new_value);
// === Accessor functions ===
// return current current_size of the list
short get_current_size();
// === Other functions ===
// return the last element, or 0 if the list is empty, with a warning output
int get_last();
// return element at the position-th position, or 0 if the list is empty, with a warning output
int get_temp(short position);
// returns if current_size == 0
bool set_temp(short position, int value);
// returns if current_size == 0
bool empty();
// returns if current_size == max_size
bool full();
// Output list separated by commas
friend ostream& operator <<(ostream& outs, const TemperatureList& list);
};
int main() {
TemperatureList temp_a;
temp_a.add_temperature(23.5);
temp_a.add_temperature(24.6);
cout << temp_a;
TemperatureList temp_b = temp_a;
cout << temp_b;
temp_a = TemperatureList();
cout << "Now there's no temperatures in a.\n";
cout << temp_a;
cout << "How about temperatures in b?\n";
cout << temp_b;
return 0;
}
void TemperatureList::operator =(const TemperatureList& another_list) {
delete[] temp;
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::TemperatureList() {
current_size = 0;
max_size = 0;
temp = NULL;
}
TemperatureList::TemperatureList(int max) : max_size(max) {
current_size = 0;
temp = new int[max];
}
TemperatureList::TemperatureList(const TemperatureList& another_list) {
current_size = another_list.current_size;
max_size = another_list.max_size;
if (current_size > 0) {
temp = new int[max_size];
for (int i = 0; i < max_size; i++) {
temp[i] = another_list.temp[i];
}
}
else {
temp = NULL;
}
}
TemperatureList::~TemperatureList() {
//cout << "== I am in destructor ==\n";
delete[] temp;
}
void TemperatureList::add_temperature(int new_value) {
if (current_size < max_size) {
temp[current_size] = new_value;
current_size++;
}
else {
cout << "Cannot add value to the list. It is full.\n";
}
}
int TemperatureList::get_last() {
if (empty()) {
cout << "The list is empty\n";
return 0;
}
else {
return temp[current_size - 1];
}
}
int TemperatureList::get_temp(short position) {
if (current_size >= position) {
return temp[position - 1];
}
else {
cout << "There is no temperature\n";
return 0;
}
}
bool TemperatureList::set_temp(short position, int value) {
if (current_size >= position) {
temp[position - 1] = value;
return true;
}
else {
return false;
}
}
short TemperatureList::get_current_size() {
return current_size;
}
bool TemperatureList::empty() {
return (current_size == 0);
}
bool TemperatureList::full() {
return (current_size == max_size);
}
ostream& operator <<(ostream& outs, const TemperatureList& list) {
int i;
for (i = 0; i < (list.current_size - 1); i++) {
outs << list.temp[i] << ",";
}
outs << list.temp[i];
return outs;
}
The logic error seems to stem from the fact that you initialize your current_size and max_size to zero. So, unless your run the overloaded constructor (wherein you’re set the max_size), every call to addTemperature() is going to fail the (current_size < max_size) check because they are both equal to zero.
I am having a problem with my program throwing an exception when inserting data at specific index's of my array. I am using a hash table, and trying to use the STL list in an array of pointers to another class that contains the data.
Since this is a Hash Table, I'm avoiding using the vector class since the size of the array should be constant. (I know the initial size that I want)
MCVE (For you) :
#ifndef HASHTABLE_H
#define HASHTABLE_H
#include <list>
#include <cstring>
#include <stdlib.h>
template <typename T1>
class HashTable
{
public:
HashTable();
void Insert(T1 var)
int FindPrime(int);
int HashFunction(string);
private:
int prime;
list<T1> *List;
int LF;
}
#endif
template <typename T1>
HashTable<T1>::HashTable()
{
List[i] = list<T1>();
}
template <typename T1>
int HashTable<T1>::FindPrime(int num)
{
bool isNotPrime = false;
for (int i=num; i < num + 25; ++i)
{
for (int j=2; j<i; ++j)
{
if (i % j == 0)
{
isNotPrime = true;
}
}
if (isNotPrime == false)
{
prime = i;
return prime;
break;
}
isNotPrime = false;
}
prime = num;
return prime;
}
template <typename T1>
long HashTable<T1>::HashFunction(string key)
{
long numkey = 0;
char word[1000];
strcpy(word,key.c_str());
word[sizeof(word) - 1] = NULL; //Ensure null is at last index of word
for(int i = 0; word[i] != NULL; ++i)
{
numkey = numkey + (word[i] * 101 + word[i]);
}
numkey = numkey % prime;
return numkey;
}
template <typename T1>
void HashTable<T1>::Insert(T1 var)
{
int index = HashFunction(var -> getKey());
List[index].push_front(var);
++LF;
cout << "Load Factor: " << LF << endl << endl;
}
from a seperate class that is determining what to do with the data:
file >> num;
hash.FindPrime(num);
file >> letter; // Get letter from file so we know what to do
if(letter == 'D' || letter == 'd') //If the letter is D, then add a new DNA Node with corresponding data to the STL List
{
file >> Label >> ID >> Seq >> Length >> Index;
cout << "Note: Adding " << Label << " ..." << endl << endl;
Sequence* ptr = new DNA(Label, ID, Seq, Length, Index);
hash.Insert(ptr);
ptr = NULL;
delete ptr;
}
Sequence Class is the base class for Several inherited classes (DNA is one of them)
Type of List[i] is list<T1>. That's why the compiler doesn't allow you to use:
List[i] = new list<T1>;
// Trying to assign a list<T1>* to a list<T1>.
You can use
List[i] = list<T1>();
or
list<T1>** List;
I'm working on a programming lab on hash tables. The code we were given handles collisions by rehashing the key (by adding one) and trying again, simple, but works for lab. The problem is that, with the raw code, it could enter an infinite loop if you add a member to a full table. We were tasked to keep this from happening.
I'm using a count for contents (contentCount) so it wont get caught up in a loop, i.e. if count >= size, it won't insert.
The header and source files are below.
hashTable.h
#pragma once
#include <iostream>
using namespace std;
const int NONE = 0;
const int EMPTY = -1;
const int DELETED = -2;
class HashTable
{
public:
// Constructors
HashTable(int size);
HashTable(const HashTable & ht);
~HashTable();
// Methods
bool Insert(int key, int value);
bool Search(int key, int &value);
bool Delete(int key);
void Print();
private:
// Private methods
int Hash(int key);
int Hash2(int index);
// Private data
int Size;
int *Value;
int *Key;
int contentCount;
};
hashTable.cpp
#include "hashTable.h"
HashTable::HashTable(int size)
{
Size = size;
Value = new int[Size];
Key = new int[Size];
for (int index=0; index < Size; index++)
{
Value[index] = NONE;
Key[index] = EMPTY;
}
}
HashTable::HashTable(const HashTable & ht)
{
contentCount = 0;
Size = ht.Size;
Value = new int[Size];
Key = new int[Size];
for (int index=0; index < Size; index++)
{
Value[index] = ht.Value[index];
Key[index] = ht.Key[index];
}
}
HashTable::~HashTable()
{
delete []Value;
delete []Key;
}
bool HashTable::Insert(int key, int value)
{
if(contentCount >= Size)
{
return false;
}
// Find desired key
int index = Hash(key);
while ((Key[index] != key) && (Key[index] != EMPTY))
index = Hash2(index);
// Insert value into hash table
Value[index] = value;
Key[index] = key;
contentCount++;
return true;
}
bool HashTable::Search(int key, int &value)
{
// Find desired key
int index = Hash(key);
while ((Key[index] != key) && (Key[index] != EMPTY))
index = Hash2(index);
// Return value from hash table
if (Key[index] == key)
value = Value[index];
return (Key[index] == key);
}
bool HashTable::Delete(int key)
{
// Find desired key
int index = Hash(key);
while ((Key[index] != key) && (Key[index] != EMPTY))
index = Hash2(index);
// Delete value from hash table
if (Key[index] == key)
{
Value[index] = NONE;
Key[index] = DELETED;
contentCount--;
return true;
}
return false;
}
int HashTable::Hash(int key)
{
return key % Size;
}
int HashTable::Hash2(int index)
{
cout << "COLLISION\n";
return (index+1) % Size;
}
void HashTable::Print()
{
cout << "Index\t" << "Value\t" << "Key\n";
for (int index=0; index < Size; index++)
cout << index << "\t"
<< Value[index] << "\t"
<< Key[index] << "\n";
}
Thanks ahead for the help!
You're initializing contentCount in the copy constructor, but in HashTable(int size), you're not.
So obviously, it will be uninitialized.
I would like to add compare++ to this code in order to count how many compares are done by this algorithm. Does the count of compare need to be incremented on each execution of the first while loop in Merge(...) and in the if and else inside the while? Are these the only locations where compare should be incremented? (I added this increment where I thought it belonged and commented out. Please ignore the swap function)
#include "MergeSort.h"
template<class ItemType>
void MergeClass<ItemType>::sort(ItemType values[], int first, int last)
// Post: The elements in values are sorted by key.
{
if (first < last)
{
int middle = (first + last) / 2;
sort(values, first, middle);
sort(values, middle + 1, last);
Merge(values, first, middle, middle + 1, last);
}
}
template<class ItemType>
void MergeClass<ItemType>::Merge(ItemType values[], int leftFirst, int leftLast,
int rightFirst, int rightLast)
// Post: values[leftFirst]..values[leftLast] and
// values[rightFirst]..values[rightLast] have been merged.
// values[leftFirst]..values[rightLast] are now sorted.
{
ItemType tempArray[5];
int index = leftFirst;
int saveFirst = leftFirst;
while ((leftFirst <= leftLast) && (rightFirst <= rightLast))
{
if (values[leftFirst] < values[rightFirst])
{
tempArray[index] = values[leftFirst];
leftFirst++;
//compare++;
}
else
{
tempArray[index] = values[rightFirst];
rightFirst++;
//compare++;
}
index++;
//compare++;
}
while (leftFirst <= leftLast)
// Copy remaining items from left half.
{
tempArray[index] = values[leftFirst];
leftFirst++;
index++;
}
while (rightFirst <= rightLast)
// Copy remaining items from right half.
{
tempArray[index] = values[rightFirst];
rightFirst++;
index++;
}
for (index = saveFirst; index <= rightLast; index++)
values[index] = tempArray[index];
}
template<class ItemType>
inline void MergeClass<ItemType>::Swap(ItemType& item1, ItemType& item2)
// Post: Contents of item1 and item2 have been swapped.
{
ItemType tempItem;
tempItem = item1;
item1 = item2;
item2 = tempItem;
}
template<class ItemType>
MergeClass<ItemType>::MergeClass()
{
compare = 0;
swap = 0;
}
template<class ItemType>
void MergeClass<ItemType>::sortPreformance()
{
cout << "Comparisons made: " << compare <<endl;
cout << "Swaps made: "<< swap <<endl;
}
If it's meant strictly for profiling, I'd put the counting logic outside of the sorting class. That is something like the following (which just counts the number of comparisons and swaps used by std::sort):
#include <iostream>
#include <algorithm>
#include <cstdlib>
using namespace std;
template<typename T>
struct CountingItem {
CountingItem(const T& val = T()) : val_(val) {}
bool operator<(const CountingItem<T>& rhs) const {
++compares;
return val_ < rhs.val_;
}
static size_t compares;
static size_t swaps;
T val_;
};
template<typename T>
size_t CountingItem<T>::compares = 0;
template<typename T>
size_t CountingItem<T>::swaps = 0;
template<typename T>
void swap(CountingItem<T>& a, CountingItem<T>& b) {
++CountingItem<T>::swaps;
std::swap(a, b);
}
int main()
{
const size_t num_items = 10000;
CountingItem<int> items[num_items];
for(int i = 0; i < num_items; i++) items[i] = rand() % 100;
sort(items, items+num_items);
cout << "Compares = " << CountingItem<int>::compares << endl;
cout << "Swaps = " << CountingItem<int>::swaps << endl;
// Reset CountingItem<int>::compares and swaps here if you're running another test
}