How to add/update/delete Department in university class? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
#include <iostream>
using namespace std;
class Professor
{
string name;
long employeeID;
string designation;
public:
Professor()
{
name = "";
employeeID = 0;
designation = "";
}
Professor(string n, long ID, string d)
{
name = n;
employeeID = ID;
designation = d;
}
void setProfessorData(string name1, long ID1,string d1)
{
name = name1;
employeeID = ID1;
designation = d1;
}
string getName()
{
return name;
}
long getID()
{
return employeeID;
}
string getDesignation()
{
return designation;
}
};
class Department
{
private:
string name;
long deptID;
Professor profList[5];
int noOfprofessors;
public:
Department()
{
name = "";
deptID = 0;
for (int i = 0; i < 5; i++)
{
profList[i].setProfessorData ("",0,"");
}
noOfprofessors = 0;
}
Department(string name1, long id1, Professor array[5], int no_of_dpt)
{
name = name1;
deptID = id1;
for (int i = 0; i < 5; i++)
{
profList[i] = array[i];
}
noOfprofessors = no_of_dpt;
}
void setDepartmentData(string n, long i, Professor arr[5], int nd)
{
name = n;
deptID = i;
for (int i = 0; i < 5; i++)
{
profList[i] = arr[i];
}
noOfprofessors = nd;
}
string getName1()
{
return name;
}
long getDeptId()
{
return deptID;
}
int getnoOfProfessors()
{
return noOfprofessors;
}
};
class University
{
private:
string name;
Department dept[5];
int numberOfDepartments;
public:
University(string n, Department array[5], int no)
{
name = n;
for (int i = 0; i > 5; i++)
{
dept[i] = array[i];
}
numberOfDepartments = no;
}
void setUniversityData(string name1, Department arr[5], int n1)
{
name = name1;
for (int i = 0; i < 5; i++)
{
dept[i] = arr[i];
}
numberOfDepartments = n1;
}
bool addDepartment(Department D)
{
}
bool deleteDepartment(string name)
{
}
bool updateDepartment(int id, string name)
{
}
};
How to add, delete, and update Department in University class?
I have provided the skeleton code. I have implemented all constructors and destructors, but I don't know how to implement addDepartment(), deleteDepartment(), and updateDepartment()`. Kindly look into this and help me to complete this task.

First off, several of your for loops are incorrect, namely the ones in the following methods:
Department::Department(string, long, Professor[5], int), should be using no_of_dpt (or better, std::min(no_of_dpt, 5)) instead of 5 for the loop counter.
Department::setDepartmentData(), should be using nd (or better, std::min(nd, 5)) instead of 5 for the loop counter.
University::University(string, Department[5], int), should be using no (or better, std::min(no, 5)) instead of 5 for the loop counter. Also, the loop needs to use < instead of >.
University::setUniversityData(), should be using n1 (or better, std::min(n1, 5)) instead of 5 for the loop counter.
That being said, you already have basic logic for adding elements to arrays, so you can implement addDepartment() by applying that logic correctly, eg:
bool addDepartment(Department D)
{
if (numberOfDepartments < 5)
{
dept[numberOfDepartments] = D;
++numberOfDepartments;
}
}
And, you can easily implement deleteDepartment(), you just need to find the index of the desired Department and shift the remaining departments down 1 element in the array, eg:
bool deleteDepartment(string name)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getName1() == name)
{
for(int j = i+1; j < numberOfDepartments; ++j)
{
dept[j-1] = dept[j];
}
--numberOfDepartments;
dept[numberOfDepartments].setDepartmentData("", 0, NULL, 0);
break;
}
}
}
Unfortunately, you cannot implement updateDepartment() with the current code you have shown. This is because University does not have access to update the Department::name field directly, and it does not have access to a Department's existing professor data in order to call Department::setDepartmentData() with just a new name.
So, you will have to fix this issue first, either by making University be a friend of Department, or by adding a Department::setName() setter, or by adding getters for the data in the Department::profList array.
However, once you have addressed that, you can then implement updateDepartment(), eg:
class Department
{
private:
string name;
...
friend class University;
public:
...
};
class University
{
private:
...
public:
...
bool updateDepartment(int id, string newName)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getDeptId() == id)
{
dept[i].name = newName;
break;
}
}
}
};
Or:
class Department
{
private:
string name;
...
public:
...
void setName(string newName)
{
name = newName;
}
};
class University
{
private:
...
public:
...
bool updateDepartment(int id, string newName)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getDeptId() == id)
{
dept[i].setName(newName);
break;
}
}
}
};
Or:
class Department
{
private:
...
Professor profList[5];
int noOfprofessors;
public:
...
Professor* getProfessors()
{
return profList;
}
int getnoOfProfessors()
{
return noOfprofessors;
}
};
class University
{
private:
...
public:
...
bool updateDepartment(int id, string newName)
{
for (int i = 0; i < numberOfDepartments; ++i)
{
if (dept[i].getDeptId() == id)
{
dept[i].setDepartmentData(newName, dept[i].getDeptId(), dept[i].getProfessors(), dept[i].getnoOfProfessors());
break;
}
}
}
};

Related

Returning an Array of pointers

I have to finish a prompt tonight for my coding class, and I believe I am writing this incorrectly. I have reviewed other stackoverflow answers, but I still lack the understanding necessary to correctly solve this. This is part of a bigger project, so I have included all code in case another function is causing this error, but in my testing only the Ballot class is giving me errors.
In getVote, if the parameter is within the used portion of the array,
return the Voter pointer that corresponds with that position.
This is supposed to be tested with:
Ballot ballot1("WI-643UWO");
const Vote *vote3 = ballot1.getVote(2);
cout << vote3 << "\n";
//header file
pragma once
#include <string>
using namespace std;
class Election {
private:
string office;
string firstCanidiateName;
string secondCanidiateName;
public:
Election(string office2, string firstCanidiateName2, string secondCanidiateName2);
string getOffice() const;
string getCandidate1() const;
string getCandidate2() const;
};
class Vote {
private:
string vOffice;
string canidiateName;
bool voteMadeInPerson;
public:
Vote(string vOffice2, string canidiateName2, bool voteMadeInPerson2);
string getOffice() const;
string getCandidate() const;
bool wasInPerson() const;
};
class Ballot {
private:
string voterID;
int votesStored;
Vote* votePointer[6];
public:
Ballot();
Ballot(string voterID2);
~Ballot();
string getVoterId() const;
int getVoteCount() const;
const Vote* getVote(int votePosition) const;
void recordVote(string office, string candidateName, bool voteInPerson);
int countInPersonVotes();
int findVote(string office) const;
};
//functions file
#include "p3.h"
#include <string>
using namespace std;
Election::Election(string office2, string firstCanidiateName2, string secondCanidiateName2) {
office = office2;
firstCanidiateName = firstCanidiateName2;
secondCanidiateName = secondCanidiateName2;
}
string Election::getOffice() const {
return office;
}
string Election::getCandidate1() const {
return firstCanidiateName;
}
string Election::getCandidate2() const {
return secondCanidiateName;
}
string Vote::getOffice() const {
return vOffice;
}
string Vote::getCandidate() const {
return canidiateName;
}
bool Vote::wasInPerson() const {
return voteMadeInPerson;
}
Vote::Vote(string vOffice2, string canidiateName2, bool voteMadeInPerson2) {
if (vOffice2.empty() == true) {
vOffice2 = "Unknown";
}
vOffice = vOffice2;
if (canidiateName2.empty() == true) {
canidiateName2 = "Write In";
}
canidiateName = canidiateName2;
voteMadeInPerson = voteMadeInPerson2;
}
string Ballot::getVoterId() const {
return voterID;
}
int Ballot::getVoteCount() const {
return votesStored;
}
const Vote* Ballot::getVote(int votePosition) const {
Vote* out;
if (votePosition > -1 && votePosition < votesStored) {
//unsure if this is proper syntax -- will need testing
out = votePointer[votePosition];
return out;
}
else {
out = nullptr;
return out;
}
}
void Ballot::recordVote(string office, string candidateName, bool voteInPerson) {
if ((votesStored + 1) < 6) {
int x = findVote(office);
if (x != -1) {
Vote* z = new Vote(office, candidateName, voteInPerson);
votePointer[votesStored] = z;
++votesStored;
}
}
}
int Ballot::countInPersonVotes() {
int count = 0;
for (int i = 0; i < votesStored; ++i) {
bool x = false;
x = votePointer[i]->wasInPerson();
if (x == true) {
count++;
}
}
return count;
}
int Ballot::findVote(string office) const {
//test to make sure this logically works
int i = 0;
bool matchCheck = false;
for (i = 0; i < votesStored; ++i) {
if (votePointer[i]->getOffice() == office) {
matchCheck = true;
return i + 1;
}
}
if (matchCheck == false) {
return -1;
}
}
Ballot::Ballot(string voterID2) {
voterID = voterID2;
votesStored = 0;
}
Ballot::Ballot() {
voterID = "Invalid ID";
votesStored = 0;
}
Ballot::~Ballot() {
/**this is what the prompt asks for, technically.
the book details that this can be achieved in a more simple matter --
using the delete[] operator.
*/
for (int i = 0; i < 6; ++i) {
delete votePointer[i];
}
}
Any help would be appreciated - I am unsure where I am messing up here. I seem to be getting a lot of read access violation errors, but we haven't touched on debugging, so I'm not necessarily sure how to identify what I did wrong. Furthermore, my functions did seem to work initially until I tried fixing it, and now it gives me a read-error almost instantly, which is concerning. And lastly - I am new to pointers, so there is a very high chance I messed up there. Thanks for any advice.

Function removes too much

I'm doing a phone registry and in it you need to be able to add, remove and show the phones on stock. I've made it possible to add in phones but whenever I add let's say 3 phones and remove the second one then both the third and second phone are deleted and I don't understand why.
This is my CellPhoneHandler.h file:
#ifndef CELLPHONEHANDLER_H
#define CELLPHONEHANDLER_H
#include "CellPhone.h"
class CellPhoneHandler
{
private:
CellPhone **phone;
int nrOfPhones;
int priceOfPhone;
int stockCapacity;
int nrOfPhonesInArr;
public:
CellPhoneHandler();
~CellPhoneHandler();
void addPhone(string brand, int nrOf, int price);
bool removePhoneFromStock(string name, int nrOf);
int getNrOfPhones() const;
int getNrOfPhonesInArr() const;
int getPrice() const;
void getPhonesAsString(string arr[], int nrOf, int priceOfPhone) const;
};
#endif // !CELLPHONEHANDLER_H
this is my CellPhoneHandler.cpp file.
#include "CellPhoneHandler.h"
CellPhoneHandler::CellPhoneHandler()
{
this->phone = nullptr;
this->nrOfPhones = 0;
this->priceOfPhone = 0;
this->stockCapacity = 0;
this->nrOfPhonesInArr = 0;
}
CellPhoneHandler::~CellPhoneHandler()
{
for (int i = 0; i < nrOfPhonesInArr; i++)
{
delete phone[i];
}
delete[] phone;
}
void CellPhoneHandler::addPhone(string brand, int nrOf, int price)
{
if (stockCapacity < nrOfPhonesInArr + 1)
{
CellPhone ** tempArray = new CellPhone*[this->nrOfPhonesInArr + 1];
for (int i = 0; i < nrOfPhonesInArr; i++)
{
tempArray[i] = this->phone[i];
}
delete[] this->phone;
this->phone = tempArray;
this->phone[this->nrOfPhonesInArr] = new CellPhone(brand, nrOf, price);
this->nrOfPhonesInArr++;
//this->stockCapacity++;
}
}
bool CellPhoneHandler::removePhoneFromStock(string name, int nrOf)
{
bool phoneFound = false;
int index = nrOfPhonesInArr;
for (int i = 0; i < nrOfPhonesInArr; i++)
{
if (this->phone[i]->getBrand() == name);
{
index = i;
phoneFound = true;
this->nrOfPhonesInArr--;
}
}
if (phoneFound == true)
{
delete phone[index];
phone[index] = nullptr;
}
return phoneFound;
}
int CellPhoneHandler::getNrOfPhones() const
{
return this->nrOfPhones;
}
int CellPhoneHandler::getNrOfPhonesInArr() const
{
return this->nrOfPhonesInArr;
}
int CellPhoneHandler::getPrice() const
{
return this->priceOfPhone;
}
void CellPhoneHandler::getPhonesAsString(string arr[], int nrOf, int priceOfPhone) const
{
for (int i = 0; i < nrOf; i++)
{
arr[i] = this->phone[i]->toString();
}
}
The problem is caused by an unwanted ;.
if (this->phone[i]->getBrand() == name); // if ends here.
The next block is executed for all items.
{
index = i;
phoneFound = true;
this->nrOfPhonesInArr--;
}
Remove that ; in the if line.

Array of derived class stored in parent class

I don't think I quite understand how to store an array of a derived class in its parent class.
I keep getting errors
Error C3646 'list': unknown override specifier
Error C2065 'list': undeclared identifier
Here is the code I have
#include <iostream>
#include <string>
using namespace std;
class GameScores
{
public:
GameEntry list[9];
void inputList(GameEntry x);
void sortList();
void removeList(int r);
void printList();
GameScores();
};
class GameEntry :public GameScores
{
public:
GameEntry(const string& n = "", int s = 0, const string d = "1/1/99");
string getName() const;
int getScore() const;
string getDate() const;
string setName(string n);
int setScore(int s);
string setDate(string d);
private:
string name;
int score;
string date;
};
GameScores::GameScores()
{
GameEntry list[9];
}
void GameScores::inputList(GameEntry x)
{
for (int i = 0; i < 10; i++)
if (x.getScore() >= list[i].getScore())
{
list[i + 1] = list[i];
list[i] = x;
}
}
void GameScores::sortList()
{
GameEntry swap;
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10 - 1; j++)
{
if (list[j].getScore() > list[j].getScore() + 1)
{
swap = list[j];
list[j] = list[j + 1];
list[j + 1] = swap;
}
}
}
}
void GameScores::removeList(int r)
{
for (int i = r; i < 10; i++)
list[i - 1] = list[i];
list[9].setScore(0);
list[9].setName(" ");
list[9].setDate(" ");
}
void GameScores::printList()
{
cout << "Top Scores" << endl;
for (int i = 0; i < 10; i++)
cout << list[i].getScore() << " " << list[i].getName() << " " << list[i].getDate() << endl;
}
GameEntry::GameEntry(const string& n, int s, const string d) // constructor
: name(n), score(s), date(d) { }
// accessors
string GameEntry::getName() const { return name; }
int GameEntry::getScore() const { return score; }
string GameEntry::getDate() const { return date; }
string GameEntry::setName(string n)
{
name = n;
}
int GameEntry::setScore(int s)
{
score = s;
}
;
string GameEntry::setDate(string d)
{
date = d;
}
int main()
{
GameEntry p1("John", 90, "9/9/98"), p2("Jane", 95, 8/21/98), p3("Bob", 60, "7/11/99"), p4("Jo", 92, "6/4/97");
GameScores topScores;
topScores.inputList(p1);
topScores.inputList(p2);
topScores.inputList(p3);
topScores.inputList(p4);
topScores.printList();
return 0;
}
This design is very questionable. What purpose is being served by making the second class inherit the first? It looks like you'd end up with each member of the array containing an additional array with all its siblings. Don't you want only one array? You need to rethink this from an earlier point.
If you really have a reason for a parent class to contain an array of the child class, maybe you should define an interface (abstract base class) that both classes implement.
To use GameEntry as a type in your GameScores class , you must forward-declare the class like so :
class GameEntry;
class GameScores
{
public:
GameEntry list[9];
void inputList(GameEntry x);
void sortList();
void removeList(int r);
void printList();
GameScores();
};

Deleting a record from array of pointers of my own class type

I have created an Employee class:
class Employee {
private:
int idNumber;
string name, department, position;
public:
Employee() {
idNumber = 0;
name = department = position = "";
}
Employee(string n, int idn) {
name = n;
idNumber = idn;
department = position = "";
}
Employee(string n, int idn, string dep, string pos) {
name = n;
idNumber = idn;
department = dep;
position = pos;
}
void setName(string n) {
name = n;
}
void setidNumber(int idn) {
idNumber = idn;
}
void setDepartment(string dep) {
department = dep;
}
void setPosition(string pos) {
position = pos;
}
string getName() {
return name;
}
int getidNumber() {
return idNumber;
}
string getDepartment() {
return department;
}
string getPosition() {
return position;
}
};
Now, i created a 2D array of Pointers of type Employee:
int n=2;
Employee **p = new Employee * [n];
for (int i=0; i < n; i++)
p[i] = new Employee;
I stored two records successfully as under:
Name ID Number Department Position
FS 30 CS BS
AT 27 CS BS
I have this code to delete the record of Employees:
string del_name;
int flag = 0;
cin.ignore();
cout << "Enter name: ";
getline(cin, del_name);
for (int i=0; i < n; i++) {
while (del_name == p[i]->getName() && i < n) {
if (del_name == p[i]->getName()) {
delete p[i];
p[i] = NULL;
--k;
++flag;
cout << "Record deleted." << endl;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
cout << "No record found having name " << del_name << "." << endl;
Now, What's the problem:
If a record is found at multiple times. It deletes successfully even if all the records gets deleted.
But if ALL the records are unique and I delete the records one by one and all the records get deleted in this way then the program gets terminated.
Also, is there any other optimized approach to delete records without using VECTORS.
I hope i have clearly explained my problem. I can provide further details if needed.
Thank you for your time
First, usage of std::vector<> or some other container object is the way to go about this. If you can write code that beats (in terms of speed) written by professional library writers, then go ahead.
Second, what is your goal? If it's to simply deallocate entries in that array depending on some criteria, the loop you wrote is overly complex.
bool recordDeleted = false;
for (int i=0; i < n; ++i)
{
if (del_name == p[i]->getName())
{
delete p[i];
p[i] = NULL;
recordDeleted = true;
}
}
if ( !recordDeleted )
{
// record not found
}

Bubblesort giving access violation

Hi everyone I am trying to finish a assignment for class where I need to sort a File full of employees by their ID number. There are 10 lines in the file each with an employees info. The order is ID LASTNAME FIRSTNAME
The program ran fine before I wrote the sort function and copied all the data properly into the array, but now after adding my sort function I keep getting a access violation with no hints as to what is causing it.
I would appreciate any help.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
class Employee
{
public:
int _id;
string _lastName;
string _firstName;
Employee()
{
_id = 0;
_lastName = "n/a";
_firstName = "n/a";
}
};
void copyFile10(Employee [], int);
void sortFile10(Employee [], int);
int main()
{
const int size10 = 10;
Employee employees10[size10];
copyFile10(employees10, size10); //1.fill array/copy file
sortFile10(employees10, size10); //2. sort
system("pause");
return 0;
}
void copyFile10(Employee employees10[], const int size)
{
ifstream data10("data_10.dat");
for(int count = 0; count < 10; count++) //1.fill array/copy file
{
data10 >> employees10[count]._id;
data10 >> employees10[count]._lastName;
data10 >> employees10[count]._firstName;
}
data10.close();
}
void sortFile10(Employee employees10[], const int size)
{
Employee buff1;
Employee buff2;
int counter = 0;
bool ordered = false;
while (ordered == false)
{
for(int count = 0; count < size-1; count++)
{
if(employees10[count]._id > employees10[count+1]._id)
{
buff1._id = employees10[count+1]._id;
buff1._lastName = employees10[count+1]._lastName;
buff1._firstName = employees10[count+1]._firstName;
buff2._id = employees10[count]._id;
buff2._lastName = employees10[count]._lastName;
buff2._firstName = employees10[count]._firstName;
employees10[count]._id = buff1._id;
employees10[count]._lastName = buff1._lastName;
employees10[count]._firstName = buff1._firstName;
employees10[count+1]._id = buff2._id;
employees10[count+1]._lastName = buff2._lastName;
employees10[count+1]._lastName = buff2._lastName;
counter++;
}
if(counter == 0)
ordered = true;
else
counter = 0;
}
}
}
for(int count = 0; count < size; count++)
{
if(employees10[count]._id > employees10[count+1]._id)
What happens here on the last iteration of the loop (i.e. when count is 9)?