对于STL中的依靠比较排序的容器,均提供了一个模板参数来传递比较函数,默认的为std::less<>。
查阅可以看到典型的使用比较函数的容器有
template, class Compare = less > class priority_queue;template < class T, // set::key_type/value_type class Compare = less , // set::key_compare/value_compare class Alloc = allocator // set::allocator_type > class set;template < class Key, // map::key_type class T, // map::mapped_type class Compare = less , // map::key_compare class Alloc = allocator > // map::allocator_type > class map;
分别是优先队列、集合、映射,当然multiset和multimap也一样。
这里以优先队列为例,分别给出三种传递方式,将比较函数从默认的less<>(升序)改成降序。
这里先看看优先队列的构造函数源码
protected: _Container c; // the underlying container _Pr comp; // the comparator functor
priority_queue(const _Myt& _Right) : c(_Right.c), comp(_Right.comp) { // construct by copying _Right } explicit priority_queue(const _Pr& _Pred) : c(), comp(_Pred) { // construct with empty container, specified comparator }
1、函数指针
bool greaterInt(const int& lhs, const int& rhs){ return lhs > rhs;}priority_queue