从C ++中的数组中删除对象? [英] Remove object from an array in C++?

查看:171
本文介绍了从C ++中的数组中删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码的简化示例:.h

Here's a simplified sample of my code : The .h

class Company {
public:
    Company();
    void addEmployee(const Employee &emp);
    void removeEmployee();

private:
    Employees *listEmployees;
};

.cpp

Company::Company(){ listEmployees = new Employees[16]; }
Company::addEmployee(const Employee &emp) {listEmployee[index]=emp;}
Company::removeEmployee(){ ??? }

我想删除存储在数组中的Employee.我尝试使用:

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];
}

其中indexEmp是我要删除的员工的索引.

Where indexEmp is the index of the employee I want to remove.

推荐答案

另一种方法是让布尔数组的长度与 Employess 的长度相同,以跟踪对象是否在特定位置是否有效.

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...

与使用 std :: vector (这应该是您的第一选择)相比,它需要做的工作要多得多.

It's a lot more work than using a std::vector, which should be your first choice.

这篇关于从C ++中的数组中删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆