你需要一點BOOST做這一切與職能工作(或者使自己的提升版本:: counting_iterator)
//for(int i = 0; i < N; ++i)
// A[i] = myFunction1(i);
std::transform(
boost::counting_iterator<int>(0),
boost::counting_iterator<int>(N),
A.begin(),
&myFunction1);
//for(int i = 0; i < N; ++i)
// B[i] = myFunction2(A[i], i);
std::transform(
A.begin(),
A.end(),
boost::counting_iterator<int>(0),
B.begin(),
&myFunction2);
//for(int i = 0; i < N; ++i)
// C[i] = myFunction3(A[i], B[i]);
std::transform(
A.begin(),
A.end(),
B.begin(),
C.begin(),
&myFunction3);
// The STL doesn't have a version of transform that takes three inputs, but given a transform_3 that does:
//for(int i = 0; i < N; ++i)
// D[i] = myFunction4(A[i], B[i], i);
transform_3(
A.begin(),
A.end(),
B.begin(),
boost::counting_iterator<int>(0),
D.begin(),
&myFunction4);
這transform_3
功能可能是這個樣子:
// Untested code
template <class input1, class input2, class input3, class output, class oper>
output transform_3 (input1 in1begin, input1 in1end, input2 in2, input3 in3, output out, oper op)
{
while (in1begin != in1end)
*(out++) = op(*(in1begin++), *(in2++), *(in3++));
return out;
}
對於它的價值,STL算法往往不lambda表達式使用跳動。你的編譯器是否支持lambda表達式? – 2011-02-23 19:41:05
@ james-mcnellis我使用GCC,但我不知道什麼是lambda表達式。 – 2011-02-23 19:44:24
你可以先看看std :: transform和std :: for_each – Erik 2011-02-23 19:46:36