您的位置:首页 > 其它

模板类 std::less

2014-03-29 20:12 211 查看
定义: 标准库中不小于或不等于的函数对象类。

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

using namespace std;
template <class T>
struct less {
bool operator() (const T& x,constT& y) const {return x<y;}
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};


    这个对象能够用于标准算法库中的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:定义结构类型。

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

#include<iostream>
#include<functional>
using namespace std;
int main()
{
int a = 3;
int b = 4;
cout << std::less<int>()(a, b) << std::endl;
return 0;

}

    结果输出为1。

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

// less example
#include <iostream> // std::cout
#include <functional> // std::less
#include <algorithm> // std::sort, std::includes

int main () {
int foo[]={10,20,5,15,25};
int bar[]={15,10,20};
std::sort (foo, foo+5, std::less<int>()); // 5 10 15 20 25
std::sort (bar, bar+3, std::less<int>()); // 10 15 20
if (std::includes (foo, foo+5, bar, bar+3, std::less<int>()))
std::cout << "foo includes bar.\n";
return 0;
}


    结果为:fooincludes bar。

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

    std::less在标准库中的很多类模板中使用,这就有点类似我们定义的宏运算,但是它比宏预算更加安全。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  标准库中function