C ++ Function object adapter (adapter function object)

C ++ Function object adapter (adapter function object)

Function object adapter will modify operation Function object.

Common adapter (adapter)

1. binder adapter (bundled adapters)

The function object binding to a specific value, can be converted to dibasic monocarboxylic function object. STL provides two binder adapter are bind1st , bind2nd

//binder1st:绑定第一个参数
	/*
		template<class Operation, class Type>
		binder1st <Operation> bind1st(
		   const Operation& _Func,
		   const Type& _Left
		);
	*/
//找到vec中第一个满足10<vec[i]的位置
find_if(vec.begin(),vec.end(),bind1st(less<int>(),10));	
//binder2nd:绑定第二个参数
	/*
		template<class Operation, class Type>
		binder1st <Operation> bind2nd(
		   const Operation& _Func,
		   const Type& _Left
		);
	*/
//找到vec中第一个满足vec[i]<10的位置
find_if(vec.begin(),vec.end(),bind2nd(less<int>(),10));

2. negator adapter (adapter inverted)

The authenticity of the value of the function object negated. STL is also provided are two: Notl () , NOT2 () corresponding to each one yuan, di- function object

/*找出所有大于或等于10的元素,可以将less<int>()的结果取反*/
while((iter=find_if(iter,vec.end(),not1(bind2nd(less<int>(),10))))!=veec.end())

3.insertion adapter (adapter insertion)

Let us avoid the use of container assignment operator. STL provides three, namely back_inserter (), inserter (), front_inserter ()
Note: The three adapt included in the header file Iterator, and can not be used in the array, because the array does not support insert

  1. back_inserter ()
    back_inserter container will push_back () function instead of the assignment operator. Of the vector, this is more suitable inserter. Back_inserter parameter itself out, it should be is the container itself.
vector<int>result_vec;
unique_copy(ivec.begin(),ivec.end(),
			back_inserter(result_vec));
  1. Inserter
    Inserter () will insert the container () function substituted assignment operator. Inserter () accepts two parameters: a container, a Iterator is, the operation starting point within the container. With vector, it would read:
vector<int>result_vec;
unique_copy(ivec.begin(),ivec.end(),
			inserter(result_vec,result_vec.end()));

  1. front_inserter
    front_inserter () will push_front container () function substituted assignment operator. The inserter applies only to the list and deque. (Using similar back_inserter ())
Published 51 original articles · won praise 6 · views 6304

Guess you like

Origin blog.csdn.net/weixin_40859716/article/details/104363761