关于函数适配器less< Type>以及bind1st和bind2nd的使用

本文介绍了C++标准库中的函数适配器,如greater、less等,以及如何使用bind1st和bind2nd进行函数绑定,以实现对字符串的降序排列和其他自定义比较操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标准库定义了一组算术,关系与逻辑对象类,另外还定义了一组函数适配器
在functional头文件中:
plus< Type>
minus< Type>
negate< Type>
not_equal_to< Type>
logical_not< Type>….等等
包括算术、关系、逻辑对象类型

sort(svec.begin(),svec.end(),greater< string>())

使用函数对象来对字符串降序排列

标准库还定义了两个求反器
not1,not2
not1(bind2nd(less_equal< int>(),10)表示不小于等于10的那些元素
关于函数绑定器bind1st和bind2nd的使用,使用例子如下:

#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;

int main () {
  int numbers[] = {10,20,30,40,50,10};
  int cx1,cx2,cx3;
  cx1 = count_if (numbers, numbers+6, bind1st(equal_to<int>(),10) );//20=x
  cx2 = count_if (numbers, numbers+6, bind1st(less<int>(),20) ); //20<x
  cx3 = count_if (numbers, numbers+6, bind1st(greater<int>(),20) );//20>x 
  cout<<cx1<<endl<<cx2<<endl<<cx3<<endl;

  cx1 = count_if (numbers, numbers+6, bind2nd(equal_to<int>(),10) );//20=x
  cx2 = count_if (numbers, numbers+6, bind2nd(less<int>(),20) ); //x<20
  cx3 = count_if (numbers, numbers+6, bind2nd(greater<int>(),20) );//x>20
  cout<<cx1<<endl<<cx2<<endl<<cx3<<endl;
  return 0;
}

/*
2
3
2

2
2
3
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值