从C++列表中删除对象

Remove Object from C++ list

本文关键字:删除 对象 列表 C++      更新时间:2023-10-16

我是C++的新手。。。我正在上一些课——一个是学生课,一个是课程课。"课程"中有一个"列表",用于添加学生对象。

我可以添加一个学生:

void Course::addStudent(Student student)
{
    classList.push_back(student); 
}

但是当我去删除一个Student时,我无法删除它。我收到了一个关于Student不能派生和运算符==(const分配器)的长错误。

void Course::dropStudent(Student student)
{
     classList.remove(student); 
}

有什么建议吗?谢谢

我指的是这个网站,了解如何添加/删除元素:http://www.cplusplus.com/reference/list/list/remove/

学生代码:

class Student {
std::string name; 
int id; 
public:
void setValues(std::string, int); 
std::string getName();
};
void Student::setValues(std::string n, int i)
{
name = n; 
id = i; 
};
std::string Student::getName()
{
    return name; 
}

完整课程代码:

class Course 
{
std::string title; 
std::list<Student> classList; //This is a List that students can be added to. 
std::list<Student>::iterator it; 
public: 
void setValues(std::string); 
void addStudent(Student student);
void dropStudent(Student student);
void printRoster();
};
void Course::setValues(std::string t)
{
    title = t;  
};
void Course::addStudent(Student student)
{
    classList.push_back(student); 
}
void Course::dropStudent(Student student)
{
    classList.remove(student);
}
void Course::printRoster()
{
    for (it=roster.begin(); it!=roster.end(); ++it)
    {
        std::cout << (*it).getName() << " "; 
    }
}

如前所述,问题在于Student缺少std::list::remove所需的operator==

#include <string>
class Student {
    std::string name; 
    int id; 
public:
    bool operator == (const Student& s) const { return name == s.name && id == s.id; }
    bool operator != (const Student& s) const { return !operator==(s); }
    void setValues(std::string, int); 
    std::string getName();
    Student() : id(0) {}
};

注意operator==operator !=是如何过载的。预计如果两个对象可以与==进行比较,那么!=也应该可以使用。检查operator!=是如何根据operator ==编写的。

还要注意,参数是作为常量引用传递的,函数本身是const

现场示例:http://ideone.com/xAaMdB

std::list::remove()删除列表中将等于的所有元素。您没有给出Student的定义,但可能没有定义operator == ()方法,因此对remove()的调用无法工作。

列表无法删除您的学生,因为它不知道如何将列表中的学生与remove方法中的学生进行比较
请注意,student是按值传递的,因此与列表中的实例不同。

您可以做的一件事是在Student中实现operator==,这将帮助列表找到您的学生。

另一种可能性(如果你不能更改Student类,尤其相关)是保存一个Student*(学生指针)的列表,然后该列表将能够比较指针,并找到你试图删除的指针。

void Course::dropStudent(Student student)
{
    list<Student>::iterator itr=classList.begin();
    list<Student>temporary;
    while(itr!=classList.end())
    {
        if(itr->id!=student.id)
        {
            temporary.push_back(itr);
        }
        itr++;
    }
    classList=temporary;
}