Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from an array in C++?

Tags:

c++

arrays

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.

like image 244
IronRabbit Avatar asked Jun 21 '26 22:06

IronRabbit


2 Answers

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.

like image 84
Miki Avatar answered Jun 23 '26 12:06

Miki


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!

like image 43
templatetypedef Avatar answered Jun 23 '26 12:06

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!