模板类 std::less

https://blog.csdn.net/lklzyy/article/details/22509695

 

模板类 std::less

2014年03月29日 20:12:05 KalvinC 阅读数:4039

定义: 标准库中不小于或不等于的函数对象类。

   下面是其在C++11中的定义:

 

 
  1. using namespace std;

  2. template <class T>

  3. struct less {

  4. bool operator() (const T& x,constT& y) const {return x<y;}

  5. typedef T first_argument_type;

  6. typedef T second_argument_type;

  7. typedef bool result_type;

  8. };

 

 

    这个对象能够用于标准算法库中的sort、merge、lower_bound等算法。函数调用参数类型必须支持比较运算符操作(operator<)。

    在上面类的定义上,包含了两个部分,一个是函数定义,一个别名定义。

    bool operator(const T&,const T&)const:是一个比较函数,比较两个参数,看第一个参数是否小于第二个,返       回真值,若第一个参数小于第二个参数,则返回true,反之false。

 

    typedef T first_argument_type:给参数类型起别名。

    typedef T second_argument_type: 同上面一样。

    typedef bool result_type:定义结构类型。

 

    定义上面上个别名,主要是在其他标准库中的模板类中使用方便。

 

 
  1. #include<iostream>

  2. #include<functional>

  3. using namespace std;

  4. int main()

  5. {

  6. int a = 3;

  7. int b = 4;

  8. cout << std::less<int>()(a, b) << std::endl;

  9. return 0;

  10.  
  11. }

 

 

    结果输出为1。

 

    看看一个标准库中的例子:

 

 
  1. // less example

  2. #include <iostream> // std::cout

  3. #include <functional> // std::less

  4. #include <algorithm> // std::sort, std::includes

  5.  
  6. int main () {

  7. int foo[]={10,20,5,15,25};

  8. int bar[]={15,10,20};

  9. std::sort (foo, foo+5, std::less<int>()); // 5 10 15 20 25

  10. std::sort (bar, bar+3, std::less<int>()); // 10 15 20

  11. if (std::includes (foo, foo+5, bar, bar+3, std::less<int>()))

  12. std::cout << "foo includes bar.\n";

  13. return 0;

  14. }

 

    结果为:fooincludes bar。

    std::includes功能为:看看foo数组的第一个到第五个数是否包含bar的第一个到第三个。运算符为后面std::less。

    std::less在标准库中的很多类模板中使用,这就有点类似我们定义的宏运算,但是它比宏预算更加安全。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值