俊介三

一天更新一点,一天积累一点

导航

C/C++ 队列的使用

Posted on 2013-03-05 14:37  俊介三在前进  阅读(253)  评论(0)    收藏  举报

队列的使用。

详情见http://www.cplusplus.com/reference/queue/

#include <stdio.h>
#include <string.h>
#include <queue>

using namespace std;

struct Node{
    Node(){}
    Node(int a, char *n, int h){
        age = a;
        strcpy(name,n);
        height = h;
    }
    int age;
    char name[20];
    int height;
}node[200];

struct cmp{
    bool operator() (const Node& n1, const Node& n2) const{
        return n1.height<n2.height;  //队头为最大的数
    }
};
struct cmp2{
    bool operator() (const int& n1, const int& n2) const{
        return n1>n2;  //队头为最小的数
    }
};

int main(){
    //普通队列 FIFO
    queue<int> q1; 
    q1.push(4); 
    q1.push(6);
    q1.push(1);
    q1.pop();
    int i = q1.front();//
    if(!q1.empty())printf("%d\n",i);//
    
    //优先队列,默认自动维护队头总是最大的队列
    priority_queue<int> q2;//基本类型才能不重载符号

    //优先队列,自动维护一个队头总是最大的队列
    priority_queue<Node, vector<Node>, cmp>q3;
    q3.push(Node(12,"Yuan",180));
    q3.push(Node(19,"Liu",130));
    q3.push(Node(22,"chen",190));
    q3.pop();
    printf("%d %s %d\n",q3.top().age,q3.top().name,q3.top().height);
    
    //优先队列,自定义比较符,决定队头最大还是最小
    priority_queue<int, vector<int>, cmp2>q4;
    q4.push(3);
    q4.push(7);
    q4.push(4);
    printf("%d\n",q4.top());
    return 0;
}