zoukankan      html  css  js  c++  java
  • STL priority_queue sort 自定义比较终极模板

     比较有两种重载,一种是类内部的bool operator<( 只有一个参数 ),当然bool operator< 也可以拿到类的外面;另外一种是写一个cmp,利用cmp返回作为sort的第三个参数,就是这样。个人觉得还是重载operator<会简单一些,这里上代码:

    #include <iostream>
    #include <stdio.h>
    #include <queue>
    #include <stdlib.h>
    #include <functional>
    #include <algorithm>
    using namespace std;
    class Node{
    public:		
        int x, y;
        Node( int a= 0, int b= 0 ):x(a),y(b) {}
        bool operator<(Node m)const{
    		return x<m.x;
    	} 
    };
    
    /*
    重载可以放在外面,不用const修饰 
    bool operator<( Node a, Node b ){
        if( a.x== b.x ) return a.y> b.y;
        return a.x> b.x; 
    }
    */
    
    int main()
    {
        priority_queue<Node> q;
        vector<Node> qq;
    	
        
        for( int i= 0; i< 10; ++i ){
        	q.push( Node( rand(), rand() ) );
        	qq.push_back( Node( rand(),rand() ) );
    	}
    	sort(qq.begin(),qq.end());
    	printf("The result of q is :
    ");
        while( !q.empty() )
        {
            cout << q.top().x << ' ' << q.top().y << endl;
            q.pop();
        }
    	printf("The result of qq is :
    ");
    	for(int i=0;i<qq.size();i++){
    		printf("%d %d
    ",qq[i].x,qq[i].y);
    	}	
        return 0;
    }
    


  • 相关阅读:
    IDEA与Eclipse
    解释器模式
    设计模式(十一)—— 策略模式
    设计模式(六)—— 装饰模式
    Java注解
    Spring源码阅读(二)—— AOP
    业务开发(八)—— Maven
    高性能MySQL笔记
    Java源码阅读(六)—— ReentrantLock
    业务开发(六)—— MyBatis框架
  • 原文地址:https://www.cnblogs.com/james1207/p/3348023.html
Copyright © 2011-2022 走看看