c++ - 从 C++ 列表中删除对象

标签 c++ list

我是 C++ 的新手...我正在制作一些类(class) - 一个用于学生,一个用于类(class)。类(class)内部有一个“列表”,可以添加学生对象。

我可以添加学生:

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

但是当我去删除一个学生时,我无法删除它。我收到一个关于 Student not be derived 的长错误以及关于 operator==(const allocator) 的错误。

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)代码:

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

关于c++ - 从 C++ 列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29378849/

相关文章:

c++ - 需要一个简单的 SNMP 库 c++

list - 在 Common Lisp 列表中交换元素

python - 在列表的开头和结尾强制执行项目

c++ - 基类函数不调用派生类函数

c++ - Visual Studio 2015 (C++) sqlite3.dll 未解析的外部符号

C++ 发布 exe 不工作代码块

c++ - 使用 C++ 与 libpq 链接错误

java - java的lists.transform可以改变列表顺序吗?

c - 在 C 中使用 typedef 时是否使用指向结构的指针

python - 如何获取列表内嵌套字典的值?