首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

operator 如何作为一个函数的参数

2012-02-29 
operator 怎么作为一个函数的参数?我c++考试里要求写一个模板函数,函数包括四个参数,一个数组,一个运算符(

operator 怎么作为一个函数的参数?
我c++考试里要求写一个   模板函数,   函数包括四个参数,   一个数组,   一个   运算符(binary   operator),   和两个整型参数(数组的最大和最小索引),这个函数可以运算数组左右数字的和,   或者所有数字的乘积。
问题是我不知道如何把operator当成参数,   在网上查了好久也没找到相关的内容。
下面是我的代码,   不能编译,   请大家伙给看看,   谢谢了
#include   <iostream>

using   std::cin;
using   std::cout;
using   std::endl;

template <typename   T>  
T   function(const   T   *   v,   operator   op,   int   min,   int   max)
{
T   result   =   v[0];
for(int   i   =   min;   i <   max;   i++)   {
result   =   result   op   v[i];
}
}  

int   main()
{
        int   v[10]   =   {1,   2,   3,   4,   5,   6,   7,   8,   9,   0};
        double   d[10]   =   {1.1,   2.2,   3.3,   4.4,   5.5,   6.6,   7.7,   8.8,   9.9,   0.7};
       
        int   k   =   function(   v,   operator+,   0,9);//call   your   function   to   compute   the   summation   of   all   elements   in   v
        double   n   =   function(   d,   operator*,0,9);//call   your   function   to   compute   the   product   of   all   elements   in   d
       
        cout   < <   k   < <   endl;
        cout   < <   std::fixed   < <   n   < <   endl;
       
        //system( "pause ");
        return   0;
}

[解决办法]
使用用函数对象

#include <iostream>

using namespace std;

template <class T, class O>
T function(const T *v, const O& op , int min, int max)
{
T result = v[min];
for (int i=min+1; i <=max; i++)
result = op(result, v[i]);
return result;
}

template <class T>
class add
{
public:
T operator()(const T& a, const T& b) const
{ return a+b; }
};

template <class T>
class mul
{
public:
T operator()(const T& a, const T& b) const
{ return a*b; }
};

int main()
{
int v[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
double d[10] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 0.7};

int k = function(v, add <int> (), 0, 9);
double n = function( d, mul <double> (), 0, 9);

cout < < k < < endl;
cout < < std::fixed < < n < < endl;

return 0;
}
[解决办法]
想想 greater <> less <>
[解决办法]
呵呵,functor,STL里面的常见技巧。C/C++里面是不能直接将运算符作为参数进行传递的,需要包装起来。原来在C里面常用的办法是函数指针,C++里面更推荐使用functor。

热点排行