函数也可以作为参数

 #include<iostream>
using namespace std;
bool comp_asc(int a,int b)
{    return a<b;
}
bool comp_desc(int a,int b)
{    return a>b;
}
void sort(int* p,int n,bool(*compare)(int,int))
{    for(int i=0;i<n;i++)
        for(int j=0;j<i;j++)
     if(compare(p[i],p[j]))
     swap(p[i],p[j]);
}
void input(int* p,int n)
{   
 cout<<"input "<<n<<" integers:";
 for(int i=0;i<5;i++)
    cin>>p[i];
}
void output(int* p,int n)
{  
 for(int i=0;i<5;i++)
    cout<<p[i]<<' ';
}
int main()
{   cout<<"input n:";
    int n,i;
 cin>>n;
    int* p=new int[n];
 input(p,n);
 cout<<"intput i:";
 cin>>i;
 switch(i){
     case 1:sort(p,n,comp_asc);
            output(p,n);
            cout<<endl;break;
  case 2:sort(p,n,comp_desc);
            output(p,n);
            cout<<endl;break;
 }
 delete[] p;
 p=NULL;
}

当然上面的compare可以换为任意名字

 void   func1(int){};//函数声明  
  void   (*func1ptr)(int);//定义一个函数指针,指向的函数接受一个整型参数,没有返回值  
  func1ptr=func1;//把函数func1(int)的地址付给函数指针func1ptr  
  (*func1ptr)(0);//调用函数func1(int)  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值