c++ - Erase operation on vector not working -
i new c++ , having difficulties getting vector.erase operation work.
i have database class such:
template <class t> class database { protected: std::vector<t> m_database; int m_counter; public: database(); virtual ~database(); // accessor methods. t& getobject(int objectid); bool exists(int objectid); // mutator methods. void add(t object); void del(int objectid); };
and in practice, using code such:
database<account> accountdatabase;
account
base class, 2 derived classes, chequingaccount
, savingsaccount
.
i inserting accounts, regardless of type (could account
, chequingaccount
, savingsaccount
) database using:
template <class t> void database<t>::add(t object) { m_database.push_back(object); ++m_counter; }
however, having issues delete operation. searching corresponding objectid
, deleting vector.
// deletes specified object database. template <class t> void database<t>::del(int objectid) { std::vector<t>& database = m_database; typename std::vector<t>::iterator = database.begin(); while (it != database.end()) { if ((*it).getid() == objectid) { = database.erase(it); } else { ++it; } } }
unfortunately delete operation not working @ all. having issues pulling derived class database, being pulled out account
type. believe these 2 issues tied noob c++ skills , bad design.
any appreciated! thanks!
edit
by not working, mean object not deleted database. apologize confusion.
the account classes:
class account { protected: int m_id; double m_balance; std::string m_name, m_type; public: account(int id, int userid, double balance = 0, std::string name = ""); // constructor. ~account(); // destructor. // accessor methods. // returns m_id aka objectid int getid() const; } class chequingaccount: public account { public: chequingaccount(int id, int userid, double balance, std::string name) : account(id, userid, balance, name) {} } class savingsaccount: public account { public: savingsaccount(int id, int userid, double balance, std::string name) : account(id, userid, balance, name) {} }
note remove function far better in terms of std::remove_if
:
auto enditerator = std::remove_if(m_database.begin(), m_database.end(), [=](t const& entry) { return entry.getid() == objectid; } ); m_database.erase(enditerator, m_database.end());
that said, version not incorrect, inefficient. "doesn't work"? note maintain separate object id in database never put id objects store.
Comments
Post a Comment