Here's a simplified sample of my code : The .h
class Company {
public:
Company();
void addEmployee(const Employee &emp);
void removeEmployee();
private:
Employees *listEmployees;
};
The .cpp
Company::Company(){ listEmployees = new Employees[16]; }
Company::addEmployee(const Employee &emp) {listEmployee[index]=emp;}
Company::removeEmployee(){ ??? }
I would like to remove an Employee stored in my array. I tried to use :
delete listEmployee[index]; //->"cannot delete expression of type 'Employees'
listEmployee[index]=NULL; //->"no viable overloaded '='"
I didn't find satisfying solution on the web. Also, I'm not very familiar with pointer and reference, maybe the error cames from this. Thanks.
EDIT : I'm NOT allowed to use vectors, I must use arrays.
EDIT2 : Thanks for your answer. Here's the solution I used :
for(int i=indexEmp;i<sizeArray-1;i++){
listEmployees[i]=listEmployees[i+1];
}
Where indexEmp is the index of the employee I want to remove.
An alternative approach would be to have an array of bool the same length of Employess to keep track if the object at a specific position is valid or not.
When you add an element, you set the corresponding value in the array, when you remove it, you reset the corresponding value.
When you access your employees, you should also check if it's valid or not.. etc...
It's a lot more work than using a std::vector, which should be your first choice.
There is no built-in way to remove an element from a C++ array. Arrays always have fixed size, so you can't add or remove elements.
You do have some other options. For example, you could use the std::vector type, which acts like an array but lets you add and remove elements. Alternatively, if you just need to store elements in some order and don't care what the order is, try using std::unordered_map or std::map.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With