Hi,
I was checking how method Vec::retain is implemented and I noticed that it performs a swap moving at the end of the vector the elements are not satisfying the passed predicate and then performs a truncate
.
Why elements are swapped instead of just copied? There is no way to get it since the truncate
throws them away.
I was wondering if it could be optimized as in STL C++ remove_if
, that doesn't perform any swap and just copy (taken from GCC source code ./libstdc++-v3/include/bits/stl_algo.h
):
template<typename _ForwardIterator, typename _Predicate>
_ForwardIterator
__remove_if(_ForwardIterator __first, _ForwardIterator __last,
_Predicate __pred)
{
__first = std::__find_if(__first, __last, __pred);
if (__first == __last)
return __first;
_ForwardIterator __result = __first;
++__first;
for (; __first != __last; ++__first)
if (!__pred(__first))
{
*__result = _GLIBCXX_MOVE(*__first);
++__result;
}
return __result;
}
Thank you.