2010-06-09 65 views

回答

0

如果你的意思是输出那么就传递数组直入一个整数的下一个函数说多少个元素有。它将传递第一个元素的地址(32位系统上的4个字节或64位系统上的8个字节),然后以4个字节传递大小。

如果幸运的话,编译器甚至会通过寄存器传递这些参数。

1

你可以给‘其他’功能,第一个功能回调到:

#include <algorithm> 
#include <iostream> 

template<typename It, typename It2, typename F1, typename F2> 
void combine(It from, It to, It2 out, F1 f1, F2 f2) { 
    for(int* p = from; p != to; ++p) { 
     *(out++) = f2(f1(*p)); 
    } 
} 

int increment(int i){ return ++i; } 

int twice(int i){ return i+i; } 

int main() { 
int ints[]={1,2,3,4}; 
int result[4]; 

combine(ints, ints+4, result, increment, twice); 
std::copy(result, result+4, std::ostream_iterator<int>(std::cout, "; ")); 

} 

事实上,这种机制可以扩展通过将这些功能倒入“头等”对象中。 STL的构建是为了实现这一点:如果你将自由函数包装在一个对象中,你可以构造一个更好的组合函子。在SGI的STL实施中,​​功能可用。

#include <functional> 


template<typename F1, typename F2> 
struct Combined : public std::unary_function 
         < typename F1::argument_type 
         , typename F2::result_type > { 

    typedef typename F2::result_type result_type; 
    typedef typename F1::argument_type argument_type; 

    Combined(F1 f1, F2 f2): f1_(f1), f2_(f2) {} 

    result_type operator()(argument_type arg) const { 
     return f2_(f1_(arg)); 
    } 

private: 
    F1 f1_; 
    F2 f2_; 
}; 

template<typename F1, typename F2> 
Combined<F1,F2> combined(F1 f1, F2 f2) { return Combined<F1,F2>(f1,f2); } 

,然后使用此功能,甚至更普遍地结合功能:

#include <iostream> 
#include <iterator> 
#include <algorithm> 

int increment(int i){ return ++i; } 
int twice(int i) { return 2*i; } 

int main() { 
    using namespace std; 
    int values[]={1,2,3,4}; 

    transform(values, values+4, ostream_iterator<int>(cout, "; "), 
       combined(ptr_fun(increment), ptr_fun(twice)) 
     ); 
    transform(values, values+4, ostream_iterator<int>(cout, "; "), 
       combined(ptr_fun(increment), 
         combined(ptr_fun(increment), ptr_fun(twice))) 
     ); 

} 
+0

谢谢老兄,这是新的! :-) – Dilawar 2010-06-09 12:57:45

相关问题