std::remove_if
移动分配迭代器值,这些值不满足给定的一元谓词(如果它们最初出现在至少一个满足给定一元谓词的迭代器值之后)。不会调用任何析构函数。
std::remove_if
的可能实现
template< typename ForwardIt, typename UnaryPredicate >
ForwardIt remove_if(ForwardIt first, ForwardIt last, UnaryPredicate p) {
first = std::find_if(first, last, p);
if (first != last)
for (ForwardIt i = first; ++i != last;)
if (!p(*i))
*first++ = std::move(*i);
return first;
}
来源: cppreference.com
代码 [Wandbox]:
#include <algorithm>
#include <iostream>
#include <vector>
struct A {
constexpr A(int a) noexcept : m_a(a) {}
constexpr A(const A&) noexcept = default;
constexpr A(A&&) noexcept = default;
~A() noexcept {
std::cout << "Destruction: " << m_a << std::endl;
}
A& operator=(const A& a) noexcept {
std::cout << "Copy assignment: " << a.m_a << std::endl;
m_a = a.m_a;
return *this;
}
A& operator=(A&& a) noexcept {
std::cout << "Move assignment: " << a.m_a << std::endl;
m_a = a.m_a;
return *this;
}
int m_a;
};
int main() {
std::vector< A > v = { 1, 2, 5, 4, 5, 5 };
std::cout << "BEGIN REMOVE" << std::endl;
auto end = std::remove_if(v.begin(), v.end(), [](const A& a) noexcept { return 5 == a.m_a; });
std::cout << "BEGIN ERASE" << std::endl;
v.erase(end, v.end());
std::cout << "END" << std::endl;
return 0;
}
Output:
Destruction: 5
Destruction: 5
Destruction: 4
Destruction: 5
Destruction: 2
Destruction: 1
BEGIN REMOVE
Move assignment: 4
BEGIN ERASE
Destruction: 4 // Could be garbage as well (unspecified, but valid, state)
Destruction: 5
Destruction: 5
END
Destruction: 1
Destruction: 2
Destruction: 4
std::partition
或stable_partition
。 - Zan Lynxstd::shared_ptr
,因此根据是否有其他指向该对象的shared_ptr
或weak_ptr
对象,erase可能会最终删除该对象。 - Pete Becker