replace_if 用法

来源:互联网 发布:小米移植网络助手 编辑:程序博客网 时间:2024/05/16 12:58

replace_iffunction template
template < class ForwardIterator, class Predicate, class T >  void replace_if ( ForwardIterator first, ForwardIterator last,                    Predicate pred, const T& new_value );
<algorithm>

Replace values in range

Sets all those elements in the range [first,last) for which pred returns true when applied to its value, to a value of new_value.

The behavior of this function template is equivalent to:

template < class ForwardIterator, class Predicate, class T >  void replace_if ( ForwardIterator first, ForwardIterator last,                    Predicate pred, const T& new_value ){  for (; first != last; ++first)    if (pred(*first)) *first=new_value;}

Parameters

first, last
Forward iterators to the initial and final positions in a sequence. The range used is [first,last), which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
pred
Unary predicate taking an element in the range as argument, and returning a value indicating the falsehood (with false, or a zero value) or truth (true, or non-zero) of some condition applied to it. This can either be a pointer to a function or an object whose class overloads operator().
new_value
Value to be set to the affected elements.

Return value

none

#include<iostream>#include<algorithm>#include<vector>using namespace std;class student{public:int key;int value;int n;student(int n):n(n){}student(){}bool operator()(student s){return s.value<n;}};int main(){vector<student>vec(5);vector<student>vec_sub;vec[0].key=1;vec[0].value=1;vec[1].key=1;vec[1].value=2;vec[2].key=5;vec[2].value=5;vec[3].key=7;vec[3].value=7;vec[4].key=4;vec[4].value=4;vec_sub.resize(vec.size());vector<student>::iterator it,p;replace_if(vec.begin(),vec.end(),student(4),vec[4]);for(it=vec.begin();it!=vec.end();it++)cout<<(*it).value<<endl;}