c++ - In Lists, is remove same as erase? -
those 2 sample examples of trying say.
first example.
std::list<someclass*> somelist; // have defined someclass m
method
remove
std::remove(somelist.begin(), somelist.end(), m);
method
erase
auto = std::find(somelist.begin(), somelist.end(), m); if (it != somelist.end()) { somelist.erase(it); }
second example.
well actual purpose of asking question,
std::list<someclass*> somelist; someclass* m = nullptr;
using same methods first example, behavior, using both methods.
here standard says:
erase:
iterator erase(const_iterator position); iterator erase(const_iterator first, const_iterator last);
invalidates iterators , references erased elements.
remove:
void remove(const t& value); template <class predicate> void remove_if(predicate pred);
erases elements in list referred list iterator i for following conditions hold: *i == value, pred(*i) != false. invalidates iterators , references erased elements.
if don't have iterator or couple of iterators used erase
, have rearrange element(s) first, using remove
better choice.
note remove
drop elements matching predicate , complexity is:
exactly size() applications of corresponding predicate
on other side, find
has still complexity o(n), stops when finds first occurrence satisfies condition.
in particular, it's complexity defined standard as:
at most
last - first
applications of corresponding predicate.
where following signature:
template<class inputiterator, class t> inputiterator find(inputiterator first, inputiterator last, const t& value);
differences in behavior: use first proposal drop elements matching predicate, use second proposal (find and) drop first element matching predicate.
differences in performance: same complexity, in worst case won't have benefit (well, in best case have benefits on large containers, o(n) irrelevant if n equal 100).
to reply last question, if want remove nullptr
s list , happen there more one, prefer remove
instead of find
/erase
.
Comments
Post a Comment