compare
function:
- sort
- 1,2,3,4,5
- (default: std::less<int>(), "<" )
- print顺序:1->2,3,4,5(按照内存从小到大地址)
- cmp使用方法:比较方法 or 比较器对象 :std::greater<int>()
-
sort (myvector.begin()+4, myvector.end(), std::greater<int>());
- 5,4,3,2,1
- 1,2,3,4,5
class:
- priority_queue
- 1,2,3,4,[5] (←内存保存顺序)(大顶堆 max heap )
- (default: std::less<int>(), "<" )
- pop顺序:[5]->4,3,2,1 (从内存最末尾开始pop)
- cmp使用方法:比较器类:
std::greater<int>
-
priority_queue<int, std::vector<int>, std::greater<int> > third (myints,myints+4);
- 小顶堆 min heap
- 1,2,3,4,[5] (←内存保存顺序)(大顶堆 max heap )
- set
- 1,2,3,4,5
- cmp使用方法:比较器类:同上priority_queue
- map
- key: 1,2,3,4,5
- cmp使用方法:比较器类:同上priority_queue
比较器类:struct:
- greater
- >
- 5,4,3,2,1
- less(default)
- <
- 1,2,3,4,5
参考:
greater:
1 template <class T> struct greater { 2 bool operator() (const T& x, const T& y) const {return x>y;} 3 typedef T first_argument_type; 4 typedef T second_argument_type; 5 typedef bool result_type; 6 };
less:
1 template <class T> struct less { 2 bool operator() (const T& x, const T& y) const {return x<y;} 3 typedef T first_argument_type; 4 typedef T second_argument_type; 5 typedef bool result_type; 6 };
自定义cmp类:
// CLASS For: map, multimap struct classcomp_char { bool operator() (const char& lhs, const char& rhs) const {return lhs<rhs;} }; // CLASS For: Type<int> : set, multiset, priority_queue // OBJ For Function: sort struct classcomp { bool operator() (const int& lhs, const int& rhs) const {return lhs<rhs;} } myobject; // Func For Function: sort bool myfunction (int i,int j) { return (i<j); } int main () { std::set<int,classcomp> set_test; // set std::multiset<int,classcomp> multiset_test; // multiset std::map<char,int,classcomp_char> map_test; // map std::multimap<char,int,classcomp_char> multimap_test; // multimap // using mycomparison: typedef std::priority_queue<int,std::vector<int>,classcomp> mypq_type; mypq_type pq_test; // priority_queue // using function as comp std::sort (myvector.begin()+4, myvector.end(), myfunction); // sort // using object as comp
// 1.myobject std::sort (myvector.begin(), myvector.end(), myobject); //sort
// 2.classcomp()
std::sort (myvector.begin(), myvector.end(), classcomp()); //sort
return 0;
}