"baibaichen" <(E-Mail Removed)> wrote in message

news:(E-Mail Removed) ups.com...

> hi, i need to implement several functions which are similar with

> transform, but just oprerate on the elements that match some condition,

> i have wirtten one by myself:

>

> template<class In,class Out,class Pred class Op>

> Out transform_if(In first,In last,Out res,Pred p,Op op)

> {

> while(first!=last){

> if (p(*first))

> *res = op(*first);

> ++first;++res;

> }

> return res;

> }

>

> but it is something subtle:

>

> 1). if the prediction return false? does output iterator increase?

> 2). how about exception safe?

> 3). efficiency problem, if we can predict the input will match the

> codition, then we have gotten the information that functor will do.

>

> my question is there any better way?

>
I'm not sure what your function could do that can't be done with

std::transform. Consider:

class func

{

public:

int operator () (int xj, int yj) const

{

if (xj == 2)

return yj; // don't change the output value

else

return 2 * xj; // change the output value

}

};

std::transform(x, x+3, y, y, func());

does the same thing as:

class pred

{

public:

bool operator () (int xj) const {return xj != 2;}

};

class op

{

public:

int operator () (int xj) const {return 2 * xj;}

};

template<class In,class Out,class Pred, class Op>

Out transform_if(In first,In last,Out res,Pred p,Op op)

{

while(first!=last){

if (p(*first))

*res = op(*first);

++first;++res;

}

return res;

}

transform_if(x, x+3, y, pred(), op());

The trick is to send the output stream to the functor along with the input

stream.

--

Cy

http://home.rochester.rr.com/cyhome/