Featured post
c++ - Erasing a container element using iterators -
my current homework assignment has me creating iterator class list. i'm stuck @ creating erase(iterator where)
function.
current code (reduced fit question):
class list { class _iter { friend class list; public: _iter(listelem *pcurr, list *plist); /* *, ->, ++, --, == , != operators overloaded */ private: listelem *pcurr_; list *plist_; }; typedef _iter iterator; iterator erase(iterator where); };
with erase being implemented so:
// precondition: list has been checked size > 0. list::iterator list::erase(list::iterator& where) { // erasing element in list. if(where == end() && == begin()) { pop_back(); // or pop_front(); return iterator(0, this); } // elem @ end if(where == end()) { pop_back(); return end(); } else { // elem @ beginning if(where == begin()) { pop_front(); return ++begin(); } } // elem somewhere between beginning , end. iterator temp(where); // node next pcurr_ should point 1 before pcurr_ where.pcurr_->next->prev = where.pcurr_->prev; // node before pcurr_ should point 1 after pcurr_ where.pcurr_->prev->next = where.pcurr_->next; // return node after pcurr_ ++temp; delete where.pcurr_; --size_; return temp; }
the first 3 cases- element, element @ end , element @ beginning- okay. coded fine , need absolutely no knowledge , private access _iter
s members. however, if element not in positions, have (seemingly) no choice violate encapsulation , change pcurr_ (element of list) directly.
is there way avoid this? looked inside stl list, used other functions _next_node_(/* stuff */)
, _prev_node_(/* stuff */)
weren't useful me. google searches give me helpful results on how use erase function, not how write myself.
question: there way in can erase element pointed iterator without having grab it's pcurr_ member?
do not use identifiers beginning underscore followed uppercase letter. reserved standard library , system writers. although writing own list class, not writing standard library.
end() 1 element past end of list, not last element. (to actual last iterator of list can l.rbegin().base() happens).
pass iterator value, not non-const reference.
why concerned modifying pcurr?
- Get link
- X
- Other Apps
Comments
Post a Comment