函式模板
<algorithm>

std::remove_if

template <class ForwardIterator, class UnaryPredicate>  ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,                             UnaryPredicate pred);
從範圍中移除元素
將範圍 [first,last) 轉換為一個新範圍,移除所有返回 true 的元素,並返回新範圍的末尾迭代器。

該函式不能改變包含元素範圍的物件的屬性(即它不能改變陣列或容器的大小):移除是透過將返回 true 的元素替換為下一個不返回 true 的元素來完成的,並透過返回一個指向應被視為其新*結束之後*元素的迭代器來指示縮短範圍的新大小。

未移除元素的相對順序被保留,而返回的迭代器與 last 之間的元素處於有效但未指定的狀態。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template <class ForwardIterator, class UnaryPredicate>
  ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,
                             UnaryPredicate pred)
{
  ForwardIterator result = first;
  while (first!=last) {
    if (!pred(*first)) {
      if (result!=first)
        *result = *first;
      ++result;
    }
    ++first;
  }
  return result;
}
元素透過*移動賦值*為其新值進行替換。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
template <class ForwardIterator, class UnaryPredicate>
  ForwardIterator remove_if (ForwardIterator first, ForwardIterator last,
                             UnaryPredicate pred)
{
  ForwardIterator result = first;
  while (first!=last) {
    if (!pred(*first)) {
      if (result!=first)
        *result = std::move(*first);
      ++result;
    }
    ++first;
  }
  return result;
}

引數

first, last
Forward iterators 指向序列的初始位置和末尾位置,該序列包含*可移動賦值*的元素。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
pred
一元函式,接受範圍內的元素作為引數,並返回一個可轉換為 bool 的值。返回的值指示該元素是否應被移除(如果為 true,則移除)。
該函式不得修改其引數。
這可以是函式指標或函式物件。

返回值

指向序列中最後一個未移除元素的下一個元素的迭代器。
範圍 first 和此迭代器之間包含序列中所有 pred 返回 false 的元素。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// remove_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::remove_if

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  int myints[] = {1,2,3,4,5,6,7,8,9};            // 1 2 3 4 5 6 7 8 9

  // bounds of range:
  int* pbegin = myints;                          // ^
  int* pend = myints+sizeof(myints)/sizeof(int); // ^                 ^

  pend = std::remove_if (pbegin, pend, IsOdd);   // 2 4 6 8 ? ? ? ? ?
                                                 // ^       ^
  std::cout << "the range contains:";
  for (int* p=pbegin; p!=pend; ++p)
    std::cout << ' ' << *p;
  std::cout << '\n';

  return 0;
}

輸出
the range contains: 2 4 6 8


複雜度

線性時間複雜度,與 firstlast 之間的*距離*成比例:對每個元素應用 pred,並可能對其中一些元素執行賦值操作。

資料競爭

範圍 [first,last) 中的物件被訪問並可能被修改。

異常

如果 pred、元素賦值或迭代器操作丟擲異常,則丟擲異常。
請注意,無效引數會導致未定義行為

另見