本文共 625 字,大约阅读时间需要 2 分钟。
1. 以greater类模板为例
templatestruct greater: public binary function { bool operator()(const T& x, const T& y) const { return x > y; }};
我们可以看到,greater原型如上,则单拿出greater来说,规定其为类模板。如果我们写greater<int>
或者greater<double>
或者单精度浮点型之类的基本数据类型,我们就将其称之为模板类。
利用这个类我们可以降序排列一个数据容器,省得我们自己去写compare函数了。不过需要注意的是,由于是利用类内重载()运算符作为类模板,从而定义模板类,最后借以定义函数对象作为函数使用,所以greater是不完全等同于函数的。它只是一个类。
因此我们在用sort函数进行排序时,如果想要调用greater等类模板,(原型:void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp))我们需要新建一个临时对象。
如下:sort ;或者sort
值得注意的是,我们需要在开头include<functional>
转载地址:http://scugf.baihongyu.com/