public member function template
<forward_list>
template <class Predicate> void remove_if (Predicate pred);
Remove elements fulfilling condition
Removes from the container all the elements for which Predicate pred returnstrue. This calls the destructor of these objects and reduces the container size by the number of elements removed.
The function callspred(*i)for each element (whereiis an iterator to that element). Any of the elements in the list for which this returnstrue, are removed from the container.
参数
- pred
- Unary predicate that, taking a value of the same type as those contained in the forward_list object, returnstruefor those values to be removed from the container, andfalsefor those remaining.
This can either be a function pointer or a function object.
示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
// forward_list::remove_if
#include <iostream>
#include <forward_list>
// a predicate implemented as a function:
bool single_digit (const int& value) { return (value<10); }
// a predicate implemented as a class:
class is_odd_class
{
public:
bool operator() (const int& value) {return (value%2)==1; }
} is_odd_object;
int main ()
{
std::forward_list<int> mylist = {7, 80, 7, 15, 85, 52, 6};
mylist.remove_if (single_digit); // 80 15 85 52
mylist.remove_if (is_odd_object); // 80 52
std::cout << "mylist contains:";
for (int& x: mylist) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
|
输出
复杂度
Linear in container size (applications of pred).
迭代器有效性
Iterators, pointers and references referring to elements removed by the function are invalidated.
All other iterators, pointers and reference keep their validity.
数据竞争
The container is modified.
The elements removed are modified. Concurrently accessing or modifying other elements is safe, although iterating through the container is not.
异常安全
If pred is guaranteed to not throw, the function never throws exceptions (no-throw guarantee).
Otherwise, if an exception is thrown, the container is left in a valid state (basic guarantee).