replace_if
Sprawdza, czy każdy element w zakresie i zastępuje go, jeśli spełnia określony predykatu.
template<class ForwardIterator, class Predicate, class Type>
void replace_if(
ForwardIterator _First,
ForwardIterator _Last,
Predicate _Pred,
const Type& _Val
);
Parametry
_First
Do przodu sterująca, wskazując położenie pierwszego elementu w zakresie, z którego elementy są zastępowane._Last
Iterację wskazując położenie, jeden obok ostatniego elementu w zakresie, z którego elementy są zastępowane._Pred
Wartość elementu jest wymieniana jest predykatu jednoelementowego, które muszą być spełnione._Val
Nową wartość jest przypisana do elementów, których stara wartość spełnia predykat.
Uwagi
Zakres odwołania musi być ważny; wszystkie wskaźniki muszą być dereferenceable i w sekwencji ostatniej pozycji jest dostępny z pierwszym przez incrementation.
Kolejność elementów nie zastąpione pozostaje stabilny.
Algorytm replace_if jest generalizacji algorytmu zastąpić, pozwalając wszelkie predykat ma być określony, a nie równości określona wartość stałą.
operator== Używana do określenia równości między elementami musi nakładać relacja równoważności między argumentów.
Złożoność jest liniowa: istnieją (_Last - _First) porównania dla równości i co najwyżej (_Last - _First) przypisań nowych wartości.
Przykład
// 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;
}
Przykładowe dane wyjściowe
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 ).
Wymagania
Nagłówek: <algorytm>
Przestrzeń nazw: std