共用方式為


replace_if

如果滿足指定的述詞,檢查在範圍內的每個項目並取代它。

template<class ForwardIterator, class Predicate, class Type>
   void replace_if(
      ForwardIterator _First, 
      ForwardIterator _Last,
      Predicate _Pred, 
      const Type& _Val
   );

參數

  • _First
    指向第一個項目位置的順向 Iterator 在項目被取代的範圍。

  • _Last
    指向超過最後一個項目的 Iterator 的位置是在項目中取代的範圍。

  • _Pred
    必須滿足的一元述詞是項目的值會被取代。

  • _Val
    指派給舊值滿足述詞之項目的新值。

備註

參考的範圍必須是有效的,任何指標必須 dereferenceable,並在序列中最後一個位置開始可取得的會增加。

不會被取代之項目的順序趨於穩定。

這個演算法是 replace_if 演算法 replace的概念,讓所有述詞指定,而不是相等至指定的常數值。

operator== 用來判斷在項目之間的相等必須強制在其運算元之間的一個層級的關聯性。

複雜的線性:有 (_Last – _First) 相等的比較和最多_Last (–) _First指派的新值。

範例

// alg_replace_if.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>

bool greater6 ( int value ) {
   return value >6;
}

int main( ) {
   using namespace std;
   vector <int> v1;
   vector <int>::iterator Iter1;

   int i;
   for ( i = 0 ; i <= 9 ; i++ )
      v1.push_back( i );

   int ii;
   for ( ii = 0 ; ii <= 3 ; ii++ )
      v1.push_back( 7 );
   
   random_shuffle ( v1.begin( ), v1.end( ) );
   cout << "The original vector v1 is:\n ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;

   // Replace elements satisfying the predicate greater6
   // with a value of 70
   replace_if ( v1.begin( ), v1.end( ), greater6 , 70);

   cout << "The vector v1 with a value 70 replacing those\n "
        << "elements satisfying the greater6 predicate is:\n ( " ;
   for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
      cout << *Iter1 << " ";
   cout << ")." << endl;
}

範例輸出

The original vector v1 is:
 ( 7 1 9 2 0 7 7 3 4 6 8 5 7 7 ).
The vector v1 with a value 70 replacing those
 elements satisfying the greater6 predicate is:
 ( 70 1 70 2 0 70 70 3 4 6 70 5 70 70 ).

需求

標題: <algorithm>

命名空間: std

請參閱

參考

replace_if (STL Samples)

標準樣板程式庫