Chinaunix首页 | 论坛 | 博客
  • 博客访问: 469156
  • 博文数量: 117
  • 博客积分: 3195
  • 博客等级: 中校
  • 技术积分: 1156
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-04 01:44
文章分类

全部博文(117)

文章存档

2012年(5)

2011年(5)

2010年(46)

2009年(61)

我的朋友

分类: C/C++

2010-08-01 09:53:52


/* 基本数据类型 */

#include <iostream>
#include <queue>
using namespace std;

int main()
{
  int i;
  int a[10];
  priority_queue<int, vector<int>, greater<int> >big;
  priority_queue<int, vector<int>, less<int> > small;

  for(i=0; i<10; i++) {
    a[i] = rand() % 10;
    big.push(a[i]);
    small.push(a[i]);
  }

  for(i=0; i<10; i++) {
    cout << a[i] << ' ';
  }
  cout << endl;

  while(!big.empty()) {
    cout << big.top() << " ";
    big.pop();
  }
  cout << endl;

  while(!small.empty()) {
    cout << small.top() << " ";
    small.pop();
  }
  return 0;
}


/× 自定义结构 ×/

#include <iostream>
#include <queue>
using namespace std;
struct stata
{
  int a, b;
  stata(int aa=0, int bb=0):a(aa),b(bb)
  {}
};

bool operator<(const stata x, const stata y)
{
  return x.a < y.a;
}

struct cmp
{
  bool operator()(stata x, stata y)
  {
    return x.a > y.a;
  }
};


int main()
{
  priority_queue <stata> big; //最大优先
  priority_queue <stata, vector<stata>, cmp> small; //最小优先

  int aa[10], bb[10];
  for(int i =0; i < 10; i++)
  {
    aa[i] = rand() % 20;
    bb[i] = rand() % 20;
    big.push(stata(aa[i], bb[i]));
    small.push(stata(aa[i], bb[i]));
  }
  cout << "from big to small:" << endl;
  while(!big.empty())
  {
    cout << big.top().a << ' ' << big.top().b << endl;
    big.pop();
  }
  cout << endl;
  cout << "from small to big:" << endl;
  while(!small.empty())
  {
    cout << small.top().a << ' ' << small.top().b << endl;
    small.pop();
  }
  cout << endl;
  return 0;
}


阅读(582) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~