从C++列表中删除对象
Remove Object from C++ list
我是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;
}
- 迭代时从向量和内存中删除对象
- C++从对象自己的类中删除对象
- 如何通过对象的类属性删除对象,并返回其对象值?
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 从列表C++中删除对象
- c++ 循环访问对象列表并删除对象
- 从对象本身的容器中删除对象
- 从尝试引用已删除函数的矢量 C++ 中删除对象
- 如何通过指向元组的共享指针删除对象
- 防止通过接口删除对象
- 在 c++ 中从内存中删除对象
- 当对象被删除时,复制被删除对象的对象如何
- 当我使用dynamic_cast并删除对象删除时,析构函数是如何工作的?
- 从内存中删除对象
- 通过C++中的删除方法自行删除对象
- C++ - 析构函数只是释放内存还是实际删除对象
- 如何通过存储在 std::list 中的指针删除对象?
- 如何通过对象参数从指针矢量中删除对象和指针
- 我可以删除对象的右值版本的函数吗?
- 使用对象的索引从矢量中删除对象