Remove Object from C++ list -
i'm new @ c++... i'm making classes - 1 student , 1 courses. there "list" inside of courses adds student objects.
i able add student:
void course::addstudent(student student) { classlist.push_back(student); }
but when go delete student, i'm not able remove it. i'm getting long error student not derived , operator==(const allocator).
void course::dropstudent(student student) { classlist.remove(student); }
any suggestions? thanks!!
i referring website how add/remove elements: http://www.cplusplus.com/reference/list/list/remove/
student code:
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; }
full course code:
class course { std::string title; std::list<student> classlist; //this list students can 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() { (it=roster.begin(); it!=roster.end(); ++it) { std::cout << (*it).getname() << " "; } }
the issue is, pointed out, student
lacking operator==
required std::list::remove
.
#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) {} };
note how both operator==
, operator !=
overloaded. expected if 2 objects can compared ==
, !=
should available used. check how operator!=
written in terms of operator ==
.
also note parameter passed const reference, , functions const
.
live example: http://ideone.com/xaamdb
Comments
Post a Comment