c++ - undeclared identifier (operator ostream) with inheritance [duplicate] - c++

This question already has answers here:
Resolve build errors due to circular dependency amongst classes
(12 answers)
Closed 5 years ago.
I can not figure out why there is an error because everything looks fine to me, I've loaded all the code, but the error is in the print operator only function. When I run the program he takes me to this function.
I have an error, but I can not understand why.
Would appreciate help.
When I run the program the error is here(in CatsPen.h):
Error 1 error C2065: 'os' : undeclared identifier
c:\users\name\documents\visual studio 2013\projects\exe8\CatsPen.h 33 1
EXE8
friend ostream& operator<<(ostream&, const CatsPen& other){
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
main:
#include <iostream>
#include "CatsPen.h"
using namespace std;
int main(){
CatsPen pen1;
int choice = -1;
while (choice == -1){
cin >> choice;
cout << "Enter your choice: " << endl;
cout << "1-add street cat " << endl;
cout << "2-add siami cat " << endl;
cout << "3-print cats " << endl;
cout << "4-print how many cats " << endl;
cout << "5-exit" << endl;
if (choice == 1){
pen1.addStreet();
}
}
system("pause");
return 0;
}
CatsPen.h:
include "Cat.h"
#include <iostream>
using namespace std;
#ifndef CatsPen_H
#define CatsPen_H
class CatsPen{
private:
StreetCat * street;
SiamiCat * siami;
int countStreet;
int countSiami;
int numOfCats;
int emptyCage;
public:
CatsPen();
~CatsPen();
int getCountCat(){
return countStreet + countSiami;
}
bool Place();
bool addStreet();
bool addSiami();
friend ostream& operator<<(ostream&, const CatsPen& other){
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
};
#endif;
CatsPen.cpp:
catsPen.h"
CatsPen::CatsPen(){
this->street = NULL;
this->siami = NULL;
this->numOfCats = 0;
this->countStreet = 0;
this->countSiami = 0;
this->emptyCage = 5;
}
CatsPen::~CatsPen(){
for (int i = 0; i < countStreet; i++)
delete &street[i];
delete[] street;
for (int i = 0; i < countStreet; i++)
delete &street[i];
delete[]siami;
}
bool CatsPen::Place(){
if (emptyCage > 0){
return true;
}
cout << "no have place in the pen" << endl;
return false;
}
bool CatsPen::addStreet(){
if (Place() == true){
if (countStreet == 0){
this->street = new StreetCat[1];
cin >> this->street[countStreet];
cout << this->street[countStreet];
}
else if (countStreet > 0){
StreetCat* copyArray = new StreetCat[this->countStreet + 1];
for (int i = 0; i < countStreet; i++){
copyArray[i] = street[i];
cin >> copyArray[countStreet];
delete[] street;
cout << copyArray[countStreet];
street = copyArray;
}
countStreet++;
emptyCage--;
}
cout << "no have place in the pen" << endl;
return false;
}
}
bool CatsPen::addSiami() {//add siami cat to the pen
if (Place() == true) {
if (countSiami == 0) {
this->siami = new SiamiCat[1];
cin >> this->siami[countSiami];
cout << siami[countSiami];
}
else if (countSiami > 0) {
SiamiCat*copyArray = new SiamiCat[this->countSiami + 1];
for (int i = 0; i < countSiami; i++)
copyArray[i] = siami[i];
cin >> copyArray[countSiami];
cout << copyArray[countSiami];
delete[]siami;
siami = copyArray;
}
countSiami++;
emptyCage--;
return true;
}
cout << "no have place in the pen" << endl;
return false;
}
thank's...

There is a typo in this definition
friend ostream& operator<<(ostream&, const CatsPen& other){
^^^
for (int i = 0; i < other.countStreet; i++){
os << other.street[i] << endl;
}
for (int i = 0; i < other.countSiami; i++){
os << other.siami[i] << endl;
}
return os;
}
The parameter name os is missed.
friend ostream& operator<<(ostream &os, const CatsPen& other){
^^^

Related

C++ roman numeral converter using class

I am having issues with trying to figure out how to declare and call my functions. I had this working without using a class, but my assignment calls for a class, romanType, to be used. Can someone please help me figure out my issues?
Here are my errors:
Severity Code Description Project File Line Suppression State
Error (active) E0020 identifier "getRoman" is undefined Garant_Project9 C:\Users\Andre\OneDrive\Desktop\C++\Garant_Project9\Garant_Project9\Garant_Project9.cpp 119
Severity Code Description Project File Line Suppression State
Warning C6001 Using uninitialized memory 'sum'. Garant_Project9 C:\Users\Andre\OneDrive\Desktop\C++\Garant_Project9\Garant_Project9\Garant_Project9.cpp 81
Severity Code Description Project File Line Suppression State
Error C3861 'getRoman': identifier not found Garant_Project9 C:\Users\Andre\OneDrive\Desktop\C++\Garant_Project9\Garant_Project9\Garant_Project9.cpp 119
Here is my code:
#include<iostream>
#include<iomanip>
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
class romanType
{
public:
void printValue(char numeral[15]);
void Menu();
void getRoman();
private:
};
void romanType::printValue(char numeral[15])
{
int RomanValues[7] = { 1000,500,100,50,10,5,1 };
char Roman[7] = { 'M','D','C','L','X','V','I' };
int number = 0, ck[15] = { 0 }, len = 0;
bool ok = false;
for (int x = 0; x < 15; x++)
if (numeral[x] != '\0')
len++; //Finding out how long the input is
else
x = 15;
for (int x = 0; x < len; x++)
{
ok = false;
for (int y = 0; y < 7; y++)
{
if (numeral[x] == Roman[y])
ok = true; // Making sure the input is all Roman numerals
}
if (!ok)
{
cout << "Sorry, the '" << numeral[x] << "' is NOT a Roman Numeral." << endl << "Try
again.." << endl << endl;
return;
}
}
for (int x = 0; x < len; x++)
{
for (int y = 0; y < 7; y++)
{
if (numeral[x] == Roman[y])
{
ck[x] = RomanValues[y];// Fill array ck with decimal value of inputted Roman #
}
}
}
for (int x = 0; x < len; x++)
{
if ((ck[x + 1] > ck[x]))
{
number += (ck[x + 1] - ck[x]); // If number is lower than next number, subtract
// So IV is 4 and VI is 6
x++;
}
else
number += ck[x]; // else add
}
cout << number << endl << endl;
}
void romanType::Menu()
{
cout << "\tRoman Numeral Values" << endl << endl;
cout << "\t\tM = 1000" << endl;
cout << "\t\tD = 500" << endl;
cout << "\t\tC = 100" << endl;
cout << "\t\tL = 50" << endl;
cout << "\t\tX = 10" << endl;
cout << "\t\tV = 5" << endl;
cout << "\t\tI = 1" << endl;
}
void romanType::getRoman()
{
char numeral[15];
do
{
Menu();
cout << endl << "Please enter a Roman Numeral.\n(Enter 'Q', to end program)" << endl;
cin >> numeral;
for (int x = 0; x < 15; x++)
numeral[x] = toupper(numeral[x]);
if (numeral[0] == 'Q')
cout << "Program terminating!" << endl;
else
printValue(numeral);
} while (numeral[0] != 'Q');
}
int main()
{
getRoman();
return 0;
}

Unable to get invalid emails

I'm unable to get invalid emails to print in my code. I'm able to call the student roster just fine but that's about it.
#include <iostream>
#include <string>
#include "student.h"
#include "degree.h"
#include "roster.h"
using namespace std;
int main()
{
const string studentData[] =
{
"A1,John,Smith,John1989#gm ail.com,20,30,35,40,SECURITY",
"A2,Suzan,Erickson,Erickson_1990#gmailcom,19,50,30,40,NETWORK",
"A3,Jack,Napoli,The_lawyer99yahoo.com,19,20,40,33,SOFTWARE",
"A4,Erin,Black,Erin.black#comcast.net,22,50,58,40,SECURITY",
};
Roster* classRoster = new Roster(numberOfStudents);
for (int i = 0; i < numberOfStudents; ++i)
{
cout << studentData[i] << "," << endl;
}
cout << endl;
cout << "Invalid emails:";
for (int i = 0; i < numberOfStudents; ++i)
{
classRoster->printInvalidEmails();
}
cout << "Average days per class for each student" << endl;
for (int i = 0; i < numberOfStudents; ++i)
{
cout << endl;
}
cout << endl;
classRoster->printByDegreeProgram();
cout << endl;
system("pause");
return 0;
}
Here is my roster.cpp
#include <iostream>
#include <string>
#include "student.h"
#include "degree.h"
#include "roster.h"
using namespace std;
Roster::Roster()
{
This->rosterSize = 0;
this->lastIndex = -1;
this->classRosterArray = nullptr;
}
Roster::Roster(int rosterSize)
{
this->rosterSize = rosterSize;
this->lastIndex = -1;
this->classRosterArray = new Student * [rosterSize];
}
void Roster::add(string studentId, string firstName, string lastName,
string
emailAddress, int age,
int daysInCourse1, int daysInCourse2, int daysInCourse3, Degree degree)
{
}
void Roster::remove(string studentId)
{
for (int i = 0; i <= lastIndex; ++i)
{
if (classRosterArray[i] == nullptr)
{
cout << "ERROR: Student with ID: " << studentId << " not found" <<
endl;
break;
}
else if (studentId == classRosterArray[i]->getStudentId())
{
classRosterArray[i] = nullptr;
cout << "Student removed" << endl;
}
}
}
void Roster::printAll()
{
for (int i = 0; i <= this->lastIndex; ++i)
{
(this->classRosterArray)[i]->print();
}
}
void Roster::printAverageDaysInCourse(string studentId)
{
bool found = false;
for (int i = 0; i <= lastIndex; ++i) {
if ((*classRosterArray[i]).getStudentId() == studentId) {
found = true;
int average = 0;
average = (classRosterArray[i]->getNumberOfDaysToCompleteCourse()
[0]
+ classRosterArray[i]->getNumberOfDaysToCompleteCourse()[1] +
classRosterArray[i]->getNumberOfDaysToCompleteCourse()[2]) /
3;
cout << "Average days it took student " << studentId << " to
complete
a course: " << average
<< " days" << endl;
}
}
if (!found) cout << "Student not found." << endl;
}
void Roster::printInvalidEmails()
{
for (int i = 0; i < numberOfStudents; ++i)
{
string email = classRosterArray[i]->getEmailAddress();
bool isBad = false;
size_t at = email.find("#");
size_t period = email.find(".");
if (at == string::npos)
{
cout << "Invalid email. Missing # symbol." << endl;
}
else if (period == string::npos)
{
cout << "Invalid email. Missing a period." << endl;
}
else if (email.find(" ") != string::npos)
{
cout << "Invalid email. Spaces not allowed." << endl;
}
}
}
void Roster::printByDegreeProgram()
{
for (int i = 0; i < degreeType; ++i)
{
cout << &Roster::printByDegreeProgram;
}
}
Roster::~Roster()
{
for (int i = 0; i < numberOfStudents; ++i)
{
delete classRosterArray[i];
}
}
I'm just starting out and am not sure if i've totally messed myself up. Any help would be greatly appreciated. I thought might have been able to figure it out and i've tried a few different times but still unable to correct.

Error happens during deleting the dynamic allocated 2d array?

I am learning c++ and made my code of Matrix generating Class with operations.
However, When I try to delete the two matrices which input by user after the whole works, it pops up the message:
"Exception thrown at 0x0F4DBF9B (ucrtbased.dll) in Matrix 1.3.exe: 0xC0000005: Access violation reading location 0xDDDDDDCD"
at "(45)the delete[] arr[i];" line, which is in the destructor.
I tried to remove the brackets, but as I need those brackets to remove arrays, it also did not work.
Do you have any idea whats going wrong here?
#include <iostream>
#include <iomanip>
using namespace std;
class Matrix
{
private:
int row, col;
int** arr;
public:
Matrix(int, int);
~Matrix();
int getRow() const;
int getCol() const;
int** getMatrixArr() const;
friend Matrix* operator+(const Matrix&, const Matrix&);
friend Matrix* operator-(const Matrix&, const Matrix&);
friend Matrix* operator*(const Matrix&, const Matrix&);
friend Matrix* operator*(const Matrix&, int);
friend ostream& operator<<(ostream&, const Matrix*);
friend istream& operator>>(istream&, const Matrix&);
};
//construct and destruct--------------------------------------------------------------------------------------------------
Matrix::Matrix(int row, int col)
{
this->row = row;
this->col = col;
arr = new int*[row];
for (int i = 0; i < row; i++)
{
arr[i] = new int[col];
}
}
Matrix::~Matrix()
{
for (int i = 0; i < row; i++)
{
delete[] arr[i];
}
delete[] arr;
}
//getters------------------------------------------------------------------------------------------------------------------
int Matrix::getRow() const
{
return row;
}
int Matrix::getCol() const
{
return col;
}
int** Matrix::getMatrixArr() const
{
return arr;
}
//operation methods(OpOv)----------------------------------------------------------------------------------------------------------
Matrix* operator+(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "calculating..." << endl;
for (int i = 0; i <m.row; i++)
{
for (int j = 0; j <m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "+" << n.arr[i][j];
sum->arr[i][j] = m.arr[i][j] + n.arr[i][j];
}
cout << endl;
}
return sum;
}
Matrix* operator-(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "caluclating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "-" << n.arr[i][j];
sum->arr[i][j] = m.arr[i][j] - n.arr[i][j];
}
cout << endl;
}
return sum;
}
Matrix* operator*(const Matrix& m, const Matrix& n)
{
Matrix* sum = new Matrix(m.row, n.col);
cout << "calculating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < n.col; j++)
{
sum->arr[i][j] = 0;
}
}
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < n.col; j++)
{
for (int t = 0; t < m.col; t++)
{
cout << setw(3) << "+" << m.arr[i][t] << "x" << n.arr[t][j];
sum->arr[i][j] += m.arr[i][t] * n.arr[t][j];
}
}
cout << endl;
}
return sum;
}
Matrix* operator*(const Matrix& m, int num)
{
Matrix* sum = new Matrix(m.row, m.col);
cout << "calculating..." << endl;
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
cout << setw(3) << m.arr[i][j] << "x" << num;
sum->arr[i][j] = m.arr[i][j] * num;
}
cout << endl;
}
return sum;
}
// input & output ---------------------------------------------------------------------------------------------------------------------
istream& operator>>(istream& is, const Matrix& m)
{
cout << "Enter the values for the Matrix (expecting: " << m.row * m.col << "): ";
for (int i = 0; i < m.row; i++)
{
for (int j = 0; j < m.col; j++)
{
is >> m.arr[i][j];
}
}
return is;
}
ostream& operator<<(ostream& os, const Matrix* m)
{
cout << "result: " << endl;
for (int i = 0; i < m->row; i++)
{
for (int j = 0; j < m->col; j++)
{
os << setw(3) << m->arr[i][j];
}
cout << endl;
}
return os;
}
//main-------------------------------------------------------------------------------------------------------------------------------------
int main()
{
int rowNum1, colNum1;
cout << "what is the row of the Matrix 1?: " << endl;
cin >> rowNum1;
cout << "What is the column for the Matrix 1?: " << endl;
cin >> colNum1;
Matrix m1(rowNum1, colNum1);
cin >> m1;
int rowNum2, colNum2;
cout << "what is the row of the Matrix 2?: " << endl;
cin >> rowNum2;
cout << "What is the column for the Matrix 2?: " << endl;
cin >> colNum2;
Matrix m2(rowNum2, colNum2);
cin >> m2;
int choice;
do
{
cout << "Now, what operation do you want to use?" << endl;
cout << "1) addition, 2) Sub action, 3)Multiplication, 4) scalar multiplication 5) quit" << endl << ":";
cin >> choice;
if (choice == 1)
{
if (m1.getRow() != m2.getRow() || m1.getCol() != m2.getCol())
{
cout << "The number of rows or columns of both Matrices are not same, you cannot add them together." << endl;
return 0;
}
else
{
Matrix * result = (m1 + m2);
cout << result << endl;
}
}
else if (choice == 2)
{
if (m1.getRow() != m2.getRow() || m1.getCol() != m2.getCol())
{
cout << "The number of rows or columns of both Matrices are not same, you cannot add them together." << endl;
return 0;
}
else
{
Matrix * result = (m1 - m2);
cout << result << endl;
}
}
else if (choice == 3)
{
if (m1.getCol() != m2.getRow())
{
cout << "Your first Matrix's number of columns and the second Matrice's number of rows are not accorded." << endl;
return 0;
}
else
{
Matrix* result = (m1 * m2);
cout << result << endl;
}
}
else if (choice == 4)
{
int value;
cout << "What is the integer value for the multiplication?: ";
cin >> value;
int MatCho;
cout << "First Matrix or Second Matrix(1 or 2)?: ";
cin >> MatCho;
if (MatCho == 1)
{
Matrix* result = (m1 * value);
cout << result << endl;
}
else if (MatCho == 2)
{
Matrix* result = (m2 * value);
cout << result << endl;
}
else
{
cout << "invalid input" << endl;
}
}
else if (choice == 5)
{
break;
}
else
{
cout << "Invalid input" << endl;
}
} while (choice != 5);
m1.~Matrix();
m2.~Matrix();
return 0;
}
Two issues here:
Never call destructor explicitly like you do with m1 and m2 here. Their destructors will be called automatically at the end of the main function in any case. So for you the destructors will run twice. On the second run, the array of pointers has already been deleted. But row, col and the pointer still has their old values and will try to access and delete already freed memory.
All your operations you do on the matrices will leak memory. You are using new inside the operator functions but never deleting the result. It is a bad habit expecting the user of a function to delete memory you have allocated. Return by value instead. This will actually not infer any performance loss, if you implement a move constructor (http://www.learncpp.com/cpp-tutorial/15-3-move-constructors-and-move-assignment/)
Remove the manual call to the destructors. As they're stack-allocated, the C++ compiler you use will handle them when you exit the main function, even if you already called them (which is what is happening).

entries of array of an object not updating

I have a class called Random with the following variables
private:
int Numbers[10];
int NrHighest;
int NrLowest;
int Index;
int IndexH;
int IndexL;
and a friend function called friend voidinsertNumbers(Random Random1)`
void insertNumbers(Random Random1)
{
string line;
int one,two,three;
int columOne[10];
int columTwo[10];
int columThree[10];
ifstream myfile("Numbers.dat");
if (myfile.is_open())
{
int i = 0;
while ( getline (myfile,line) )
{
sscanf(line.c_str(),"%i %i %i",&one,&two,&three);
columOne[i] = one;
columTwo[i] = two;
columThree[i] = three;
i++;
}
myfile.close();
}
else cout << "Unable to open file";
switch(run)
{
case 0 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columOne[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
case 1 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columTwo[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
case 2 :
{
for(int i = 0;i < 10;i++)
{
Random1.Numbers[i] = columThree[i];
cout << Random1.Numbers[i] << endl;
};
break;
}
}
run ++;
};
I have a cout << Random1.Numbers[i] << endl; to check if the numbers are saved to Random1.Numbersand the output is
Output
But the problem come when I try to display the objects here
cout << Random1;
cout << Random2;
cout << Random3;
calling the overloaded function which is also a friend function friend ostream &operator<<( ostream &output,const Random & Random1);
ostream &operator<<( ostream &output,const Random & Random1)
{
for(int i = 0;i<10;i++)
{
cout << Random1.Numbers[i] << " ";
}
cout << endl << Random1.NrHighest << endl << Random1.NrLowest << endl << Random1.Index << endl << Random1.IndexH << endl << Random1.IndexL << endl;
return output;
};
I get the Defauts values set here
Random()
{
Numbers = {0,0,0,0,0,0,0,0,0,0};
NrHighest = 0;
NrLowest = 0;
Index = 0;
IndexH = 0;
IndexL = 0;
};
Rather than the new vaules, heres the output of the overloaded operator<< function Output
I can seem to figure out why the objects doesn't get updated.If you neem more info please ask.
Thanks in advance.
In your function void insertNumbers(Random Random1) you are adding values to Random1 but you are passing it by value. Hence, when this function is called with a Random instance, it makes a copy of it, adds values to it and finally destroys it. You will solve this problem by passing Random1 by reference: void insertNumbers(Random &Random1)

Class template, allow user to define type C++

I am doing a project about open addressed hash tables using vectors. One aspect of this project is to use templates to allow the user to define a type for the vector. I have implemented the template and it works if I create an object before compiling, however I cannot figure out how to allow the user to decide the type during runtime.
The program is object orientated and the type has to be passed into the constructor. At first I thought simple if statements would work, however I have since learned that this does not work. Can anyone help me with this problem? Thanks
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <class T>
class OpenHash
{
private:
vector <T> hashTab;
vector <int> emptyCheck;
int hashF(string);
public:
OpenHash(int);
int getVectorCap();
int addRecord (T);
int sizeHash();
int find(T);
int printHash();
int deleteEntry(T);
};
template <class T>
OpenHash<T>::OpenHash(int vecSize)
{
hashTab.clear();
hashTab.resize(vecSize);
emptyCheck.resize(vecSize);
for (int i=0; i < emptyCheck.capacity(); i++)
{
emptyCheck.at(i) = 0;
}
}
template <class T>
int OpenHash<T>::getVectorCap()
{
int cap = hashTab.capacity();
int capE = emptyCheck.capacity();
cout << cap << capE;
return 0;
}
template <class T>
int OpenHash<T>::hashF (string key)
{
int ascii = 0, hasVal = 0;
for (int i = 0; i < key.size(); i++)
{
ascii += key[i];
}
hasVal = ascii % hashTab.capacity();
return hasVal;
}
template <class T>
int OpenHash<T>::addRecord(T key)
{
if (sizeHash() == emptyCheck.size())
{
cout << "Your hash table is full cannot add any more records" << endl;
}
else
{
bool findPos = false;
for (int j=0; j<hashTab.capacity(); j++)
{
if (hashTab.at(j) == key)
{
cout << "Element ready exists in hashtable" << endl;
return 0;
}
}
int hashVal = hashF(key);
for (int i=hashVal; i<emptyCheck.capacity(); i++)
{
if (emptyCheck.at(i) == 0)
{
hashTab.at(i) = key;
emptyCheck.at(i) = 1;
cout << "Element added at" << '[' << i << ']' << endl;
findPos = true;
return 0;
}
else
{
cout << "Collision probing through..." << endl;
}
}
if (findPos == false)
{
for (int x=0; x<emptyCheck.capacity(); x++)
{
if (emptyCheck.at(x) == 0)
{
hashTab.at(x) = key;
emptyCheck.at(x) = 1;
cout << "Element added at" << '[' << x << ']' << endl;
findPos=true;
return 0;
}
}
cout << "Element could not be added" << endl;
}
}
return 1;
}
template <class T>
int OpenHash<T>::sizeHash()
{
int elementsFilled = 0;
for (int i = 0; i<emptyCheck.capacity(); i++)
{
if (emptyCheck.at(i) != 0)
{
elementsFilled++;
}
}
return elementsFilled;
}
template <class T>
int OpenHash<T>::find(T key)
{
int hashVal = hashF(key);
bool findLoop = false;
for (int i=hashVal; i < hashTab.capacity(); i++)
{
if (hashTab.at(i) == key && emptyCheck.at(i) == 1)
{
cout << "Element found at position: " << '[' << i << ']' << endl;
cout << key << endl;
findLoop = true;
return 0;
}
else
{
cout << "Element not found at position! Probing through..." << endl;
}
}
if (findLoop == false)
{
for (int j = 0; j < hashTab.capacity(); j++)
{
if (hashTab.at(j) == key && emptyCheck.at(j) != 0)
{
cout << "Element found at position: " << '[' << j << ']' << endl;
cout << key << endl;
findLoop = true;
return 0;
}
}
cout << "Entry not found" << endl;
}
return 1;
}
template <class T>
int OpenHash<T>::deleteEntry(T toDel)
{
int hashVal = hashF(toDel);
bool foundDel = false;
for (int i = hashVal; i<hashTab.capacity(); i++)
{
if (hashTab.at(i) == toDel)
{
emptyCheck.at(i) = 0;
foundDel = true;
cout << "Entry deleted!" << endl;
return 0;
}
}
if (foundDel == false)
{
for (int j=0; j<hashTab.capacity(); j++)
{
if (hashTab.at(j) == toDel)
{
emptyCheck.at(j) = 0;
foundDel = true;
cout << "Entry deleted!" << endl;
return 0;
}
}
cout << "The member to delete was not found" << endl;
}
return 1;
}
template <class T>
int OpenHash<T>::printHash()
{
if (sizeHash() == 0)
{
cout << "No elements filled to print!" << endl;
}
for (int i=0; i<emptyCheck.capacity(); i++)
{
if (emptyCheck.at(i) != 0)
{
cout << "Record at:" << '[' << i << ']' << hashTab.at(i) << endl;
}
}
return 0;
}
int main ()
{
cout << "Please input the size of your HashTable" << endl;
int vecSize = 0;
cin >> vecSize;
OpenHash<string> newTable(vecSize);
bool menu = true;
char choice;
while (menu == true)
{
cout << "Welcome to the open address hash table program, please input your choice:" << endl;
cin >> choice;
if (choice == 'a')
{
cout << "Please type in the record you wish to add:" << endl;
string rec;
getline(cin, rec);
newTable.addRecord(rec);
}
if (choice == 's')
{
cout << "Number of elements filled: " << newTable.sizeHash() << endl;
}
if (choice == 'f')
{
cout << "Please enter the string you wish to find" << endl;
string key;
getline(cin, key)
newTable.find(key);
}
if (choice == 'p')
{
cout << "Printing table..." << endl;
newTable.printHash();
}
if (choice == 'd')
{
cout << "Please input the item you wish to delete:" << endl;
string toDel;
getline(cin, toDel)
newTable.deleteEntry(toDel);
}
if (choice == 'x')
{
cout << "Thankyou" << endl;
menu = false;
}
}
return 0;
}
Templates are "decided" during compile time. They cannot be decided dynamically at run-time.
If you want to support certain types (e.g. int, double, char, etc.), you can declare them explicitly in your program and they will be compiled, but only the types you support (or others that you use in your program) will be available for the user to "pick":
template<typename T>
class MyTemplateClass { ... };
class template MyTemplateClass<int>;
class template MyTemplateClass<double>;
class template MyTemplateClass<char>;
int main()
{
// if user wants to create a new int version:
MyTemplate<int> myInt;
// etc ...
return 0;
}